From 82bf0c9346a5856333a6ac23a5986151768f3e1a Mon Sep 17 00:00:00 2001 From: Collin Rijock Date: Tue, 20 Oct 2026 00:00:59 +0000 Subject: [PATCH] Canvases in any browser: Canvas App at /canvas/, ?instance= on the canvas room socket People who are not on Copper can now use the linked Canvas Cloud's canvases from a browser, through the same proxy Copper uses: - GET /canvas/ serves Canvas App (copper-browser/canvas-app's web build, vendored as crates/copper-cloud/assets/canvas-app.html by packaging/sync-canvas-app.sh). Same origin, so its REST calls need no CORS (copper-cloud grants none, and the gate refuses preflights). - The gate accepts the instance credential as ?instance= on /v1/canvases/{id}/ws upgrades only: a browser cannot set headers on a WebSocket. Query strings are never logged, and the canvas link strips instance= (like token=) before forwarding, so Canvas Cloud never sees it. - /join/{token} links browsers to /canvas/#/join/{token} under the Copper button. Tests: gate unit tests, the proxy's query stripping, a browser-style room socket end to end through the mock Canvas Cloud (accepted with the query, 401 without or with a wrong one, nothing of ours forwarded), /canvas/ headers and redirect, the landing link. Found by Felipe's canvas-cloud e2e. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + Cargo.toml | 1 + README.md | 3 + crates/canvas-link/src/landing.rs | 9 ++- crates/canvas-link/src/proxy.rs | 21 ++++- crates/copper-cloud/Cargo.toml | 1 + crates/copper-cloud/assets/canvas-app.html | 94 ++++++++++++++++++++++ crates/copper-cloud/src/canvas_app.rs | 49 +++++++++++ crates/copper-cloud/src/lib.rs | 5 +- crates/copper-cloud/tests/canvas_app.rs | 30 +++++++ crates/copper-cloud/tests/canvas_link.rs | 42 ++++++++++ crates/core/Cargo.toml | 1 + crates/core/src/app.rs | 68 +++++++++++++--- docs/canvas-link.md | 12 +-- docs/canvas.md | 27 ++++++- packaging/sync-canvas-app.sh | 24 ++++++ 16 files changed, 364 insertions(+), 25 deletions(-) create mode 100644 crates/copper-cloud/assets/canvas-app.html create mode 100644 crates/copper-cloud/src/canvas_app.rs create mode 100644 crates/copper-cloud/tests/canvas_app.rs create mode 100755 packaging/sync-canvas-app.sh diff --git a/Cargo.lock b/Cargo.lock index c136273..abea55f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -647,6 +647,7 @@ dependencies = [ "copper-cloud-canvas-link", "copper-cloud-canvas-migrate", "copper-cloud-core", + "form_urlencoded", "futures", "hex", "reqwest", @@ -730,6 +731,7 @@ dependencies = [ "axum", "axum-server", "base64 0.22.1", + "form_urlencoded", "futures", "governor", "hex", diff --git a/Cargo.toml b/Cargo.toml index c97c231..52a5fe7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,7 @@ uuid = { version = "1", features = ["v4", "v7", "serde"] } time = { version = "0.3", features = ["serde", "serde-well-known", "formatting", "parsing", "macros"] } base64 = "0.22" hex = "0.4" +form_urlencoded = "1" bytes = "1" # crypto diff --git a/README.md b/README.md index 0a70a63..7c412df 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,9 @@ Shared canvases (live Yjs rooms, chat, mentions, invites, share links) are serve proxies the unchanged canvas API to it as the signed-in user, so Coppers need no update. See [docs/canvas-link.md](docs/canvas-link.md); upgrading a 0.10.x (or older) instance with canvases: [docs/canvas-migration.md](docs/canvas-migration.md). +People who are not on Copper open shared canvases in any browser at `https://HOST/canvas/` +([Canvas App](https://github.com/copper-browser/canvas-app)), and share links offer it too +([docs/canvas.md](docs/canvas.md#canvas-app-canvas)). People can join with **company single sign-on** (Google Workspace or any OpenID Connect provider): share one `https://HOST/start` page, they install Copper and click *Continue with diff --git a/crates/canvas-link/src/landing.rs b/crates/canvas-link/src/landing.rs index 8a97410..bd0a562 100644 --- a/crates/canvas-link/src/landing.rs +++ b/crates/canvas-link/src/landing.rs @@ -2,7 +2,8 @@ //! the old canvas crate. It is merged at the application root (outside `/v1`, so no instance //! key is needed) and deliberately touches neither the database nor Canvas Cloud: it only //! checks the token's shape and hands it to Copper as -//! `copper://canvas/join/{token}?cloud={host}`. +//! `copper://canvas/join/{token}?cloud={host}`, or to Canvas App in the browser as +//! `/canvas/#/join/{token}` (`copper_cloud::canvas_app`). use axum::extract::Path; use axum::http::{header, HeaderMap, HeaderValue, Uri}; @@ -108,9 +109,11 @@ pub async fn join_landing(Path(token): Path, uri: Uri, headers: HeaderMa }) }); let html = match href { + // Not on Copper: Canvas App, which this server serves at `/canvas/`, joins in the browser. Some(href) => format!( - "Open canvas in Copper

Canvas share link

Open this canvas in Copper to continue.

Open this canvas in Copper
", - escape_html(&href) + "Open canvas in Copper

Canvas share link

Open this canvas in Copper to continue.

Open this canvas in Copper
Not on Copper? Open it in your browser
", + escape_html(&href), + escape_html(&percent_encode_component(&token)) ), None => "Open canvas in Copper

Canvas share link

Open this link in Copper to continue.

".to_owned(), }; diff --git a/crates/canvas-link/src/proxy.rs b/crates/canvas-link/src/proxy.rs index aa8423d..12655ed 100644 --- a/crates/canvas-link/src/proxy.rs +++ b/crates/canvas-link/src/proxy.rs @@ -273,12 +273,18 @@ pub(crate) fn is_ws_path(path: &str) -> bool { .is_some_and(|id| !id.is_empty() && !id.contains('/')) } -/// The query string minus every `token=` parameter (Copper's session token for WebSocket -/// tooling); `None` when nothing is left. +/// The query string minus Copper's own credentials, which never go to Canvas Cloud: every +/// `token=` (the session token, for WebSocket tooling and browsers) and `instance=` (the gate +/// credential a browser's room socket carries, `copper_cloud_core::app::INSTANCE_QUERY`); +/// `None` when nothing is left. pub(crate) fn forwarded_query(query: Option<&str>) -> Option { + let ours = |kv: &str| { + let key = kv.split_once('=').map_or(kv, |(k, _)| k); + key == "token" || key == copper_cloud_core::app::INSTANCE_QUERY + }; let kept: Vec<&str> = query? .split('&') - .filter(|kv| !kv.is_empty() && *kv != "token" && !kv.starts_with("token=")) + .filter(|kv| !kv.is_empty() && !ours(kv)) .collect(); (!kept.is_empty()).then(|| kept.join("&")) } @@ -301,6 +307,15 @@ mod tests { Some("tokens=1&x=%20") ); assert_eq!(forwarded_query(Some("token&q=1")).as_deref(), Some("q=1")); + // A browser's room socket: neither the session nor the gate credential goes upstream. + assert_eq!( + forwarded_query(Some("token=t&instance=ck_x")).as_deref(), + None + ); + assert_eq!( + forwarded_query(Some("instance=k&full=true&instances=2")).as_deref(), + Some("full=true&instances=2") + ); } #[test] diff --git a/crates/copper-cloud/Cargo.toml b/crates/copper-cloud/Cargo.toml index 452661c..8a3ad0d 100644 --- a/crates/copper-cloud/Cargo.toml +++ b/crates/copper-cloud/Cargo.toml @@ -48,6 +48,7 @@ uuid.workspace = true zeroize.workspace = true [dev-dependencies] +form_urlencoded.workspace = true futures.workspace = true reqwest.workspace = true tokio-tungstenite.workspace = true diff --git a/crates/copper-cloud/assets/canvas-app.html b/crates/copper-cloud/assets/canvas-app.html new file mode 100644 index 0000000..139903a --- /dev/null +++ b/crates/copper-cloud/assets/canvas-app.html @@ -0,0 +1,94 @@ + + + + + + + + + Canvas + + + + +
+
+ + diff --git a/crates/copper-cloud/src/canvas_app.rs b/crates/copper-cloud/src/canvas_app.rs new file mode 100644 index 0000000..9354089 --- /dev/null +++ b/crates/copper-cloud/src/canvas_app.rs @@ -0,0 +1,49 @@ +//! Canvas App at `/canvas/`: the canvas in any browser, for people who are not on Copper +//! (`copper-browser/canvas-app`, its `dist/web/index.html`, vendored as `assets/canvas-app.html` +//! by `packaging/sync-canvas-app.sh`). Served from the server's own origin so its REST calls +//! need no CORS (the server grants none, and the gate would refuse a preflight); it reaches +//! the linked Canvas Cloud through the same `/v1/canvases…` proxy Copper uses, and its room +//! socket carries the gate credential as `?instance=` +//! (`copper_cloud_core::app::INSTANCE_QUERY`), since a browser cannot set headers on a +//! WebSocket. The page is one self-contained file with its own CSP in a `` tag. + +use axum::http::{header, HeaderValue, StatusCode}; +use axum::response::{IntoResponse, Redirect, Response}; +use axum::routing::get; +use axum::Router; +use copper_cloud_core::state::SharedState; + +/// The vendored page. +pub static PAGE: &[u8] = include_bytes!("../assets/canvas-app.html"); + +/// `/canvas` → `/canvas/`, and the page at `/canvas/`. +pub fn router() -> Router { + Router::new() + .route("/canvas", get(|| async { Redirect::permanent("/canvas/") })) + .route("/canvas/", get(page)) +} + +async fn page() -> Response { + let mut resp = (StatusCode::OK, PAGE).into_response(); + let h = resp.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/html; charset=utf-8"), + ); + // Revalidate, so an upgraded server serves its new page at once. + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")); + h.insert( + header::X_CONTENT_TYPE_OPTIONS, + HeaderValue::from_static("nosniff"), + ); + h.insert( + header::REFERRER_POLICY, + HeaderValue::from_static("no-referrer"), + ); + // Only framing is restricted here; everything else is the page's own `` policy. + h.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static("frame-ancestors 'none'"), + ); + resp +} diff --git a/crates/copper-cloud/src/lib.rs b/crates/copper-cloud/src/lib.rs index 03efbc1..fdbadcc 100644 --- a/crates/copper-cloud/src/lib.rs +++ b/crates/copper-cloud/src/lib.rs @@ -5,6 +5,7 @@ pub mod admin; pub mod admin_addons; pub mod admin_addons_cli; pub mod admin_api; +pub mod canvas_app; pub mod cli; pub mod doctor; pub mod portal; @@ -17,7 +18,8 @@ use copper_cloud_core::state::SharedState; /// The full HTTP app: core (`/healthz`, `/v1` auth/pairing/devices/sync) + the canvas API /// proxied to the linked Canvas Cloud behind the instance gate, the admin API at -/// `/admin/api` (cookie sessions, not gated), the `/join/{token}` share-link landing page, the +/// `/admin/api` (cookie sessions, not gated), the `/join/{token}` share-link landing page, +/// Canvas App at `/canvas/` (the canvas in any browser), the /// SSO onboarding page at `/start` and the embedded admin portal for every other path; auth /// rate limiters and request tracing/metrics around everything. Starts the canvas link's /// background tasks (event bridge, user reconcile, outbox) when called inside a tokio runtime. @@ -31,6 +33,7 @@ pub fn build_app_with_link(state: SharedState) -> (Router, CanvasLink) { let root = Router::new() .nest("/admin/api", admin_api::router()) .merge(CanvasLink::landing_router()) + .merge(canvas_app::router()) .route("/start", axum::routing::get(start::start)) .fallback(portal::serve); let app = copper_cloud_core::app_with(state, link.router(), root) diff --git a/crates/copper-cloud/tests/canvas_app.rs b/crates/copper-cloud/tests/canvas_app.rs new file mode 100644 index 0000000..f43456a --- /dev/null +++ b/crates/copper-cloud/tests/canvas_app.rs @@ -0,0 +1,30 @@ +//! Canvas App at `/canvas/`: the vendored page, ungated, its own headers, never the portal. + +mod common; + +use common::*; + +#[tokio::test] +async fn serves_canvas_app() { + let s = start().await; + let r = s.http.get(s.url("/canvas/")).send().await.unwrap(); + assert_eq!(r.status(), 200); + let h = r.headers().clone(); + assert_eq!(h["content-type"], "text/html; charset=utf-8"); + assert_eq!(h["cache-control"], "no-cache"); + assert_eq!(h["x-content-type-options"], "nosniff"); + assert_eq!(h["referrer-policy"], "no-referrer"); + // Only framing is restricted by the server; the page's CSP does the rest. + assert_eq!(h["content-security-policy"], "frame-ancestors 'none'"); + let body = r.text().await.unwrap(); + assert!(body.contains("id=\"web-root\""), "the Canvas App build"); + assert_eq!(body.len(), copper_cloud::canvas_app::PAGE.len()); + + let no_redirect = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap(); + let r = no_redirect.get(s.url("/canvas")).send().await.unwrap(); + assert_eq!(r.status(), 308); + assert_eq!(r.headers()["location"], "/canvas/"); +} diff --git a/crates/copper-cloud/tests/canvas_link.rs b/crates/copper-cloud/tests/canvas_link.rs index 9540544..802d966 100644 --- a/crates/copper-cloud/tests/canvas_link.rs +++ b/crates/copper-cloud/tests/canvas_link.rs @@ -622,6 +622,43 @@ async fn next_data(ws: &mut Ws) -> Message { } } +/// Canvas App's room socket: a browser cannot set headers on a WebSocket, so the session +/// and the gate credential both ride in the query. +#[tokio::test] +async fn browser_websocket_carries_the_gate_credential_in_the_query() { + let (s, _c, m, ana, _bob) = setup().await; + let key: String = form_urlencoded::byte_serialize(s.key().as_bytes()).collect(); + let url = |q: &str| format!("ws://{}/v1/canvases/c1/ws?{q}", s.addr); + + let (mut ws, _) = + tokio_tungstenite::connect_async(url(&format!("token={}&instance={key}", ana.token))) + .await + .expect("browser socket accepted"); + // Neither the session nor the gate credential goes upstream. + let last = m.st.requests_for("/v1/canvases/c1/ws").pop().unwrap(); + assert_eq!(last.query, None, "token= and instance= stripped"); + assert_eq!(last.headers["x-canvas-user"], ana.user_id); + ws.send(Message::Binary(vec![1, 2, 3].into())) + .await + .unwrap(); + assert_eq!( + next_data(&mut ws).await, + Message::Binary(vec![1, 2, 3].into()) + ); + drop(ws); + + // No credential, or a wrong one, is the gate's 401 as with a header. + for q in [ + format!("token={}", ana.token), + format!("token={}&instance=ck_nope", ana.token), + ] { + let (status, body) = + http_error(tokio_tungstenite::connect_async(url(&q)).await.unwrap_err()); + assert_eq!(status, 401, "{q}"); + assert_eq!(body["error"], "instance_key"); + } +} + #[tokio::test] async fn websocket_pipe() { let (s, _c, m, ana, _bob) = setup().await; @@ -1107,4 +1144,9 @@ async fn join_landing_page_is_public() { assert_eq!(r.headers()["cache-control"], "no-store"); let html = r.text().await.unwrap(); assert!(html.contains(&format!("copper://canvas/join/{token}"))); + // People who are not on Copper join in the browser, with Canvas App at /canvas/. + assert!( + html.contains(&format!("href=\"/canvas/#/join/{token}\"")), + "{html}" + ); } diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 48cda32..474ff3a 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -32,6 +32,7 @@ uuid.workspace = true time.workspace = true base64.workspace = true hex.workspace = true +form_urlencoded.workspace = true aes-gcm.workspace = true argon2.workspace = true sha2.workspace = true diff --git a/crates/core/src/app.rs b/crates/core/src/app.rs index f9e6216..45a61df 100644 --- a/crates/core/src/app.rs +++ b/crates/core/src/app.rs @@ -5,7 +5,6 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use axum::extract::{OriginalUri, Request, State}; -use axum::http::HeaderValue; use axum::middleware::{from_fn_with_state, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::get; @@ -26,6 +25,11 @@ pub const INSTANCE_HEADER: &str = "x-copper-instance"; /// [`crate::agents::AGENT_PAIR_PATH`] are ungated too. pub const PAIR_PATH: &str = "/v1/auth/pair"; +/// Query parameter that may carry the gate credential on a canvas room socket +/// (`/v1/canvases/{id}/ws`) instead of [`INSTANCE_HEADER`]: a browser cannot set headers on a +/// WebSocket (Canvas App, `/canvas/`). Nowhere else; request logs never record query strings. +pub const INSTANCE_QUERY: &str = "instance"; + /// The admin login route (rate limited with its own per-IP bucket). pub const ADMIN_LOGIN_PATH: &str = "/admin/api/login"; @@ -132,24 +136,42 @@ pub fn is_gated(path: &str) -> bool { && !crate::sso::is_sso_path(path) } +/// Whether `path` is a canvas room socket, `/v1/canvases/{id}/ws`. +pub fn is_canvas_socket(path: &str) -> bool { + path.strip_prefix("/v1/canvases/") + .and_then(|rest| rest.strip_suffix("/ws")) + .is_some_and(|id| !id.is_empty() && !id.contains('/')) +} + +/// The [`INSTANCE_QUERY`] value of a query string, percent-decoded. +fn query_credential(query: Option<&str>) -> Option { + form_urlencoded::parse(query?.as_bytes()) + .find(|(k, _)| k == INSTANCE_QUERY) + .map(|(_, v)| v.into_owned()) +} + /// Middleware: every gated path (see [`is_gated`]) must present a valid credential in /// `X-Copper-Instance` — the shared instance key (only while `access_mode = open`, compared -/// in constant time) or a valid access key — else 401 `{"error":"instance_key"}`. The -/// accepted credential is attached as a [`GateIdentity`] extension. +/// in constant time) or a valid access key — else 401 `{"error":"instance_key"}`. A canvas +/// room socket without the header may carry it as `?instance=` instead ([`INSTANCE_QUERY`]). +/// The accepted credential is attached as a [`GateIdentity`] extension. pub async fn instance_gate( State(state): State, mut req: Request, next: Next, ) -> Response { - if !is_gated(req.uri().path()) { + let path = req.uri().path(); + if !is_gated(path) { return next.run(req).await; } - let presented = req - .headers() - .get(INSTANCE_HEADER) - .map(HeaderValue::as_bytes) - .unwrap_or_default(); - match gate_identity(&state, presented).await { + let presented: Vec = match req.headers().get(INSTANCE_HEADER) { + Some(value) => value.as_bytes().to_vec(), + None if is_canvas_socket(path) => query_credential(req.uri().query()) + .unwrap_or_default() + .into_bytes(), + None => Vec::new(), + }; + match gate_identity(&state, &presented).await { Ok(Some(identity)) => { req.extensions_mut().insert(identity); next.run(req).await @@ -290,6 +312,32 @@ mod tests { assert!(!instance_key_matches(b"abcd", b"abc")); } + #[test] + fn canvas_sockets() { + assert!(is_canvas_socket("/v1/canvases/0192aa/ws")); + assert!(is_canvas_socket("/v1/canvases/personal/ws")); + for p in [ + "/v1/canvases/ws", + "/v1/canvases//ws", + "/v1/canvases/a/b/ws", + "/v1/canvases/a/state", + "/v1/canvases", + "/v1/sync/ws", + ] { + assert!(!is_canvas_socket(p), "{p}"); + } + } + + #[test] + fn instance_from_query() { + assert_eq!( + query_credential(Some("token=t&instance=ck_a%2Bb")).as_deref(), + Some("ck_a+b") + ); + assert_eq!(query_credential(Some("token=t")), None); + assert_eq!(query_credential(None), None); + } + #[test] fn gated_paths() { for p in [ diff --git a/docs/canvas-link.md b/docs/canvas-link.md index 9f2baf5..b04e63d 100644 --- a/docs/canvas-link.md +++ b/docs/canvas-link.md @@ -65,7 +65,7 @@ Nothing changes while a Canvas Cloud is linked and reachable: | Live room | the same y-websocket protocol and close codes (`4403` removed, `4404` deleted, `1001` shutdown, …) | | Notifications | `event: canvas` frames on `GET /v1/sync/events` with `{"type":"canvas","canvas_id","kind"}`, same kinds ([below](#event-bridge)) | | `GET /v1/info` | same `name`/`version`/limits; `features` gains `"canvas_link"`, and a new `"canvas": {"linked": bool}` object | -| `/join/{token}` | the same `copper://canvas/join/{token}?cloud={host}` landing page, served by copper-cloud | +| `/join/{token}` | the `copper://canvas/join/{token}?cloud={host}` landing page, served by copper-cloud, with a link to Canvas App (`/canvas/#/join/{token}`) for browsers | Clients gate canvas features on the server **version** (share links/people ≥ 0.3.0, invite reminders ≥ 0.5.0, mentions ≥ 0.6.0), not on `features`, so nothing has to be negotiated. @@ -92,7 +92,7 @@ For each request (`crates/canvas-link/src/proxy.rs`): 2. **Load the link** (decrypted settings cached 5 s; changes made through the admin API apply at once, CLI changes within 5 s). None, or `enabled = false` → `503 canvas_unavailable`. -3. **Forward** to `{canvas cloud url}/v1{same path}{same query minus every token= parameter}`. +3. **Forward** to `{canvas cloud url}/v1{same path}{same query minus every token= and instance= parameter}`. ### Headers @@ -101,7 +101,8 @@ For each request (`crates/canvas-link/src/proxy.rs`): | request | `Content-Type`, `Accept`, `If-Match`, `If-None-Match`, `If-Modified-Since`, `If-Unmodified-Since`, `If-Range` | `Authorization` (the Copper session), `Cookie`, `X-Copper-Instance`, hop-by-hop headers, everything else | `Authorization: Bearer `, `X-Canvas-User: `, `X-Forwarded-For: ` (as resolved by copper-cloud, honouring `trust_proxy`) | | response | status, body (streamed), `Content-Type`, `Cache-Control`, `ETag`, `Last-Modified`, `Location`, `Retry-After`, `Content-Disposition` | everything else | — | -The `?token=` query parameter (Copper's session token for WebSocket tooling) is consumed by +The `?token=` query parameter (Copper's session token for WebSocket tooling and browsers) and +`?instance=` (the gate credential a browser's room socket carries, below) are consumed by copper-cloud and removed; all other parameters (`q`, `limit`, `sv`, `unread`, `full`, `ids`, `types`, …) pass unchanged. Redirects from Canvas Cloud are not followed. @@ -151,7 +152,7 @@ Canvas Cloud at least as new as the canvas API your Coppers expect. before (`crates/canvas-link/src/ws.rs`): 1. copper-cloud first opens the **upstream** WebSocket to the same path on Canvas Cloud - (`ws://` or `wss://`, query minus `token=`, app key + `X-Canvas-User` + `X-Forwarded-For`, + (`ws://` or `wss://`, query minus `token=` and `instance=`, app key + `X-Canvas-User` + `X-Forwarded-For`, HTTP/1.1, 15 s budget). 2. If Canvas Cloud refuses the handshake with an HTTP status (`403`, `404`, …), Copper gets that status and body **without** an upgrade — exactly what the old server did for @@ -490,7 +491,8 @@ instance runs, canvases are `503`); `FAIL` = linked but unreachable or the key i - **Copper users authenticate to copper-cloud only** (instance gate + session), exactly as before. Canvas Cloud trusts copper-cloud's `X-Canvas-User` assertion for this app's users; - it never sees a Copper session token (the `Authorization` header and `?token=` are stripped). + it never sees a Copper session token or gate credential (the `Authorization` and + `X-Copper-Instance` headers, `?token=` and `?instance=` are stripped). - **What the app key can do** on Canvas Cloud: act as any user of this app (every Copper user) on the whole canvas API; create, update, disconnect and delete this app's users (with `trust_email`, provisioning an email that already has a Canvas Cloud account links that diff --git a/docs/canvas.md b/docs/canvas.md index c41cbf6..b0b8664 100644 --- a/docs/canvas.md +++ b/docs/canvas.md @@ -135,9 +135,30 @@ copper-cloud exports `canvas_link_ws_pipes` and `canvas_link_events_total` ## Web share-link landing page -Still served by copper-cloud, unchanged: `GET /join/{token}` (no gate, no database, no -Canvas Cloud call) hands off to `copper://canvas/join/{token}?cloud={host}` -(`crates/canvas-link/src/landing.rs`). +Still served by copper-cloud: `GET /join/{token}` (no gate, no database, no Canvas Cloud call) +hands off to `copper://canvas/join/{token}?cloud={host}` (`crates/canvas-link/src/landing.rs`). +Under the Copper button it links to `/canvas/#/join/{token}` for people who are not on Copper. + +## Canvas App (`/canvas/`) + +`GET /canvas/` serves [Canvas App](https://github.com/copper-browser/canvas-app): the canvas in +any browser. It is one self-contained file, vendored as +`crates/copper-cloud/assets/canvas-app.html`. `packaging/sync-canvas-app.sh [REF]` updates it; +`--check` compares it. The route is ungated, like the landing page, and holds no data. + +The app reaches the linked Canvas Cloud through the same proxy Copper uses. It runs on the +server's own origin, so its REST calls need no CORS, which copper-cloud never grants. To use it, +a person pastes a link code (the gate credential, e.g. an access key from the portal) and signs +in. + +Its room socket can't send headers, so it carries both credentials in the query, +`?token=…&instance=…`. The gate accepts `instance` on `/v1/canvases/{id}/ws` only +(`INSTANCE_QUERY`), request logs never record query strings, and neither parameter goes +upstream. + +Headers: `Cache-Control: no-cache`, `nosniff`, `Referrer-Policy: no-referrer`, and CSP +`frame-ancestors 'none'`; the rest of its policy is the page's own `` CSP. `/canvas` +redirects (308) to `/canvas/`. ## Security model diff --git a/packaging/sync-canvas-app.sh b/packaging/sync-canvas-app.sh new file mode 100755 index 0000000..5cc9c5b --- /dev/null +++ b/packaging/sync-canvas-app.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Vendor Canvas App (copper-browser/canvas-app, dist/web/index.html) as +# crates/copper-cloud/assets/canvas-app.html, which the server serves at /canvas/. +# packaging/sync-canvas-app.sh [REF] fetch REF (default main) from GitHub +# packaging/sync-canvas-app.sh --from FILE copy a local build +# packaging/sync-canvas-app.sh --check [REF] exit 1 if the vendored copy differs +set -euo pipefail +cd "$(dirname "$0")/.." +dest=crates/copper-cloud/assets/canvas-app.html +check=0 +if [[ "${1:-}" == --check ]]; then check=1; shift; fi +tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT +if [[ "${1:-}" == --from ]]; then + cp "$2" "$tmp" +else + ref=${1:-main} + curl -fsSL "https://raw.githubusercontent.com/copper-browser/canvas-app/$ref/dist/web/index.html" -o "$tmp" +fi +grep -q 'id="web-root"' "$tmp" || { echo "not a Canvas App build" >&2; exit 2; } +if (( check )); then + cmp -s "$tmp" "$dest" && echo "canvas-app.html is up to date" || { echo "canvas-app.html differs from ${ref:-the given file}" >&2; exit 1; } +else + cp "$tmp" "$dest" && echo "vendored $(wc -c <"$dest") bytes into $dest" +fi