From fa9d8c1a1da766f13ed7ef74dea6ceb3095b0372 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sun, 15 Nov 2026 06:52:45 -0600 Subject: [PATCH] id(web): send selected files to another server (#5346) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Web adapter for the #5345 server-to-server transfer, now that the transfer module has landed (PR #7905): - POST /api/files/send: carries only references (file name, destination node ID, optional dest name / replace flag) — this server performs the transfer itself through id_sync::transfer::send_file with its own endpoint identity, so no bytes pass through the browser. Success is answered only from the transfer receipt (destination confirmed blob completion + name registration). Structured errors: 400 empty name / invalid dest, 404 unknown file, 409 conflict (refused before any bytes move), 502 transfer failed (incl. an unallowlisted destination denying the send), 503 when the serving process wired no endpoint. - AppState gains transfer_endpoint; id serve passes its node endpoint through web_routers_with_surface. Destination authorization is the destination's own write policy against the source server, exactly as for CLI/REPL sends. - File-list bulk action bar gains a destination node ID input and a "Send to server…" action; main.ts sends each selected file with one POST and counts a file as sent only on an OK response with a well-shaped receipt (isSendFileResponse guard, #7837 pattern). - WEB.md route table updated. Tests: - id-web send_file_tests (6): 400/503/404 validation, plus an in-process two-server probe through the handler — send copies the blob and registers the name (source untouched), retry is idempotent (already_present), conflict refuses by default and replace archives + lands, unallowlisted destination denies and gains no name. - vitest file-op-responses: isSendFileResponse guard cases. - Full id-web lib suite: 672 passed, 1 pre-existing failure (test_load_asset_urls_from_manifest, also failing on clean main — web/dist manifest not built in a bare worktree). - tsc --noEmit pass. Clippy not run to completion locally: the pooled target dir mixes rustc 1.99.0 artifacts with the 1.99.1 clippy driver (E0514 on untouched crates). Queue task 9495. --- pkgs/id/WEB.md | 1 + pkgs/id/crates/id-cli/src/commands/serve.rs | 1 + pkgs/id/crates/id-web/Cargo.toml | 1 + pkgs/id/crates/id-web/src/lib.rs | 21 +- pkgs/id/crates/id-web/src/routes.rs | 46 ++ .../crates/id-web/src/routes/file_handlers.rs | 426 ++++++++++++++++++ pkgs/id/crates/id-web/src/templates.rs | 2 + pkgs/id/web/src/file-op-responses.test.ts | 36 +- pkgs/id/web/src/file-op-responses.ts | 28 ++ pkgs/id/web/src/main.ts | 64 ++- 10 files changed, 623 insertions(+), 3 deletions(-) diff --git a/pkgs/id/WEB.md b/pkgs/id/WEB.md index 6acb8ec702..8df11d33b6 100644 --- a/pkgs/id/WEB.md +++ b/pkgs/id/WEB.md @@ -249,6 +249,7 @@ Three DaisyUI terminal-inspired themes with `#000000` black backgrounds. Switch | `/api/new` | POST | Create new file | | `/api/rename` | POST | Rename file (with optional archive) | | `/api/copy` | POST | Copy file to new name | +| `/api/files/send` | POST | Send file to another server (server-side transfer, #5346) | | `/api/download` | POST | Download file content | | `/api/delete` | POST | Soft-delete file | | `/api/restore` | POST | Restore deleted file (404 if missing, 409 if not deleted) | diff --git a/pkgs/id/crates/id-cli/src/commands/serve.rs b/pkgs/id/crates/id-cli/src/commands/serve.rs index fc146feb6d..223c41dd1d 100644 --- a/pkgs/id/crates/id-cli/src/commands/serve.rs +++ b/pkgs/id/crates/id-cli/src/commands/serve.rs @@ -2244,6 +2244,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { surfaces, Some(groups_log.clone()), seitan_state, + Some(endpoint.clone()), ) .await?; publication_surface = Some(surface); diff --git a/pkgs/id/crates/id-web/Cargo.toml b/pkgs/id/crates/id-web/Cargo.toml index f4403deb47..7412f61217 100644 --- a/pkgs/id/crates/id-web/Cargo.toml +++ b/pkgs/id/crates/id-web/Cargo.toml @@ -34,6 +34,7 @@ id-groups = { path = "../id-groups", default-features = false } id-store = { path = "../id-store", default-features = false } id-sync = { path = "../id-sync", default-features = false } id-worlds = { path = "../id-worlds", default-features = false } +iroh = "1" iroh-base = "1" iroh-blobs = "0.103" redb = "=4.3.0" diff --git a/pkgs/id/crates/id-web/src/lib.rs b/pkgs/id/crates/id-web/src/lib.rs index 14d6170969..2091aaa69d 100644 --- a/pkgs/id/crates/id-web/src/lib.rs +++ b/pkgs/id/crates/id-web/src/lib.rs @@ -338,6 +338,13 @@ impl PublicationMounts { pub struct AppState { /// The blob store for accessing files. pub store: Store, + /// This node's own iroh endpoint, when the serving process wired one + /// in (#5346): the server-to-server transfer behind the web send + /// route (`POST /api/files/send`) runs with this endpoint's identity, + /// exactly like the meta protocol's `Send` handler (#5345). `None` + /// for states built outside `id serve` (tests, embedded surfaces) — + /// the send route then answers 503 rather than inventing an identity. + pub transfer_endpoint: Option, /// State for collaborative editing sessions. pub collab: Arc, /// Asset URLs (with cache-busting hashes). @@ -460,6 +467,7 @@ impl AppState { ) -> anyhow::Result { Ok(Self { store, + transfer_endpoint: None, collab: Arc::new(CollabState::new()), assets: load_asset_urls(), peers, @@ -484,6 +492,14 @@ impl AppState { seitan: SeitanState::default(), }) } + + /// Wire the serving node's own endpoint in as the transfer identity + /// for the web send route (#5346). `id serve` passes its endpoint + /// through [`web_routers_with_surface`]; see + /// [`AppState::transfer_endpoint`]. + pub fn set_transfer_endpoint(&mut self, endpoint: Option) { + self.transfer_endpoint = endpoint; + } } /// Load asset URLs from the embedded manifest. @@ -658,6 +674,7 @@ pub async fn web_routers( surfaces, groups_log, seitan, + None, ) .await?; Ok(routers) @@ -736,8 +753,9 @@ pub async fn web_routers_with_surface( surfaces: Vec>, groups_log: Option, seitan: SeitanState, + transfer_endpoint: Option, ) -> anyhow::Result<(Vec, WebSurfaceFactory)> { - let state = match local_events { + let mut state = match local_events { Some(events) => { AppState::with_local_events( store, @@ -762,6 +780,7 @@ pub async fn web_routers_with_surface( .await? } }; + state.set_transfer_endpoint(transfer_endpoint); let surface = WebSurfaceFactory { state: state.clone(), world: world.clone(), diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index 3af0e86f0c..c2ac75efee 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -605,6 +605,9 @@ fn create_router_inner(state: AppState) -> Router { .route("/api/new", post(new_file_handler)) .route("/api/rename", post(rename_handler)) .route("/api/copy", post(copy_handler)) + // Server-to-server send (#5346): the browser carries only file + // references; this node's server performs the transfer itself. + .route("/api/files/send", post(send_file_handler)) .route("/api/download", post(download_handler)) .route("/api/delete", post(delete_handler)) .route("/api/restore", post(restore_handler)) @@ -2007,6 +2010,49 @@ struct CopyResponse { hash: String, } +/// Request body for sending a stored file to another server (#5346). +/// +/// The browser carries only references — the file name here, the +/// destination's node ID there — never file bytes: this server performs +/// the transfer itself, with its own identity, through the shared +/// transfer module from #5345 ([`id_sync::transfer::send_file`]). +#[derive(Debug, Deserialize)] +struct SendFileRequest { + /// Name of the stored file on this server. + name: String, + /// Destination server's node ID (64 hex characters), as exposed by + /// the peers surface. + dest: String, + /// Name to register on the destination. Defaults to `name`. + dest_name: Option, + /// Whether an existing, different destination file may be archived + /// and replaced. Conflicts refuse by default, as in CLI/REPL. + #[serde(default)] + replace: bool, +} + +/// Response from sending a file to another server (#5346). +/// +/// Returned only after the destination has confirmed blob completion +/// and name registration (the transfer module's receipt), so a 200 is +/// never a send that did not land. +#[derive(Debug, Serialize)] +struct SendFileResponse { + /// Name of the file on this (source) server. + name: String, + /// Name registered on the destination. + dest_name: String, + /// Destination server's node ID. + dest: String, + /// Content hash that was transferred. + hash: String, + /// The destination already had the name pointing at this hash; + /// nothing was pushed (a retry of the same send is safe). + already_present: bool, + /// An existing, different destination file was archived and replaced. + replaced: bool, +} + /// Request body for downloading editor content. #[derive(Debug, Deserialize)] struct DownloadRequest { diff --git a/pkgs/id/crates/id-web/src/routes/file_handlers.rs b/pkgs/id/crates/id-web/src/routes/file_handlers.rs index 87888a04cd..612445e2c5 100644 --- a/pkgs/id/crates/id-web/src/routes/file_handlers.rs +++ b/pkgs/id/crates/id-web/src/routes/file_handlers.rs @@ -946,6 +946,147 @@ pub(super) async fn copy_handler( } } +/// Send one stored file to another server (`POST /api/files/send`, #5346). +/// +/// The web adapter for the #5345 transfer: the request carries only +/// references (file name, destination node ID), and this server performs +/// the transfer itself through [`id_sync::transfer::send_file`] with its +/// own endpoint identity — no bytes pass through the browser. Caller +/// authorization is the web surface's own guard (the same one every +/// file-mutation route sits behind); the destination authorizes *this +/// server* under its write policy, exactly as for a CLI/REPL send, so an +/// unallowlisted destination denies the registration and the send fails. +/// Success is answered only from the transfer receipt, which exists +/// only after the destination confirmed blob completion and name +/// registration. +pub(super) async fn send_file_handler( + State(state): State, + Json(req): Json, +) -> Response { + let name = req.name.trim().to_owned(); + if name.is_empty() { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ + "error": "File name cannot be empty", + "reason": "empty_name", + })), + ) + .into_response(); + } + let dest_id: EndpointId = match req.dest.trim().parse() { + Ok(id) => id, + Err(_) => { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ + "error": "Destination must be a server node ID (64 hex characters)", + "reason": "invalid_dest", + })), + ) + .into_response(); + } + }; + let dest_name = req + .dest_name + .map(|n| n.trim().to_owned()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| name.clone()); + tracing::info!( + "[routes] send_file_handler: name={}, dest={}, dest_name={}, replace={}", + name, + dest_id, + dest_name, + req.replace + ); + let Some(endpoint) = state.transfer_endpoint.clone() else { + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ + "error": "This server cannot initiate server-to-server transfers (no endpoint configured)", + "reason": "transfer_unavailable", + })), + ) + .into_response(); + }; + let hash = match state.store.tags().get(&name).await { + Ok(Some(tag)) => tag.hash, + Ok(None) => { + return ( + StatusCode::NOT_FOUND, + Json(serde_json::json!({ + "error": "File not found", + "reason": "not_found", + })), + ) + .into_response(); + } + Err(err) => { + tracing::error!("[routes] send lookup failed for '{name}': {err}"); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ + "error": "Failed to look up file", + "reason": "lookup_failed", + })), + ) + .into_response(); + } + }; + match id_sync::transfer::send_file( + &state.store, + &endpoint, + iroh::EndpointAddr::from(dest_id), + &name, + hash, + &dest_name, + req.replace, + ) + .await + { + Ok(receipt) => { + tracing::info!( + "[routes] File sent: {} -> {}:{}, hash={}, already_present={}, replaced={}", + name, + receipt.dest, + receipt.dest_name, + receipt.hash, + receipt.already_present, + receipt.replaced + ); + Json(SendFileResponse { + name, + dest_name: receipt.dest_name, + dest: receipt.dest.to_string(), + hash: receipt.hash.to_string(), + already_present: receipt.already_present, + replaced: receipt.replaced, + }) + .into_response() + } + Err(err) => { + let message = format!("{err:#}"); + // The transfer module refuses a conflicting destination name + // before moving any bytes; that refusal is the caller's to + // resolve (retry with replacement), not a server fault. + let (status, reason) = if message.contains("refusing to replace") { + (StatusCode::CONFLICT, "conflict") + } else { + (StatusCode::BAD_GATEWAY, "transfer_failed") + }; + tracing::warn!("[routes] send of '{name}' to {dest_id} failed: {message}"); + ( + status, + Json(serde_json::json!({ + "error": message, + "reason": reason, + })), + ) + .into_response() + } + } +} + /// Download the current editor content in the requested format. /// /// Supports two formats: @@ -1451,3 +1592,288 @@ pub(super) async fn archive_original_tag( } } } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod send_file_tests { + use std::sync::Arc; + + use axum::{body::to_bytes, extract::State}; + use iroh::address_lookup::memory::MemoryLookup; + use iroh::endpoint::{Endpoint, RelayMode, presets}; + use iroh::protocol::Router; + use iroh_blobs::{BlobsProtocol, api::Store, store::mem::MemStore}; + use iroh_docs::protocol::Docs; + use iroh_gossip::net::Gossip; + + use super::*; + use crate::AppState; + + /// An `AppState` over an in-memory store, on `endpoint`, with that + /// endpoint wired in as the transfer identity (as `id serve` does). + async fn state_on(endpoint: Endpoint, ns: &str) -> (AppState, Store, Docs) { + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, ns, dir.path().join("meta")) + .await + .unwrap(), + ); + let mut state = AppState::new( + store.clone(), + None, + ns.to_owned(), + tags, + [7; 32], + dir.path().join(".identity.redb"), + ) + .await + .unwrap(); + state.set_transfer_endpoint(Some(endpoint)); + (state, store, docs) + } + + async fn plain_endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() + } + + async fn put_named(store: &Store, name: &str, data: &[u8]) -> iroh_blobs::Hash { + let outcome = store.blobs().add_bytes(data.to_vec()).await.unwrap(); + store + .tags() + .set(iroh_blobs::api::Tag::from(name.to_owned()), outcome.hash) + .await + .unwrap(); + outcome.hash + } + + async fn send(state: AppState, name: &str, dest: &str, replace: bool) -> Response { + send_file_handler( + State(state), + Json(SendFileRequest { + name: name.to_owned(), + dest: dest.to_owned(), + dest_name: None, + replace, + }), + ) + .await + } + + async fn response_json(response: Response) -> serde_json::Value { + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap() + } + + const SOME_NODE: &str = "abababababababababababababababababababababababababababababababab"; + + #[tokio::test] + async fn empty_name_is_a_400() { + let (state, _store, _docs) = state_on(plain_endpoint().await, "send-t-empty").await; + let response = send(state, " ", SOME_NODE, false).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(response_json(response).await["reason"], "empty_name"); + } + + #[tokio::test] + async fn invalid_destination_is_a_400() { + let (state, _store, _docs) = state_on(plain_endpoint().await, "send-t-dest").await; + let response = send(state, "report.txt", "not-a-node-id", false).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(response_json(response).await["reason"], "invalid_dest"); + } + + #[tokio::test] + async fn no_transfer_endpoint_is_a_503() { + let endpoint = plain_endpoint().await; + let dest = endpoint.id().to_string(); + let (mut state, _store, _docs) = state_on(endpoint, "send-t-noep").await; + state.set_transfer_endpoint(None); + let response = send(state, "report.txt", &dest, false).await; + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + response_json(response).await["reason"], + "transfer_unavailable" + ); + } + + #[tokio::test] + async fn missing_file_is_a_404() { + let endpoint = plain_endpoint().await; + let dest = endpoint.id().to_string(); + let (state, _store, _docs) = state_on(endpoint, "send-t-404").await; + let response = send(state, "nope.txt", &dest, false).await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!(response_json(response).await["reason"], "not_found"); + } + + /// A destination node serving the meta + blobs protocols with a + /// write policy admitting only `allowed` — the in-process half of + /// the two-server probe, mirroring `LocalNode::serve`. + struct DestNode { + endpoint: Endpoint, + store: Store, + router: Router, + _docs: Docs, + } + + async fn dest_node(lookup: &MemoryLookup, allowed: EndpointId, ns: &str) -> DestNode { + let endpoint = plain_endpoint().await; + let store: Store = MemStore::new().into(); + let gossip = Gossip::builder().spawn(endpoint.clone()); + let docs = Docs::memory() + .spawn(endpoint.clone(), store.clone(), gossip) + .await + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + let tags = Arc::new( + TagStore::init_in(&docs, ns, dir.path().join("meta")) + .await + .unwrap(), + ); + let access = id_core::access::AccessPolicy::restricted([allowed]); + let mut meta = id_sync::protocol::MetaProtocol::new( + &store, + None, + tags, + access.clone(), + endpoint.id(), + None, + ); + if let Some(inner) = Arc::get_mut(&mut meta) { + inner.endpoint = Some(endpoint.clone()); + } + let blobs = BlobsProtocol::new(&store, Some(id_core::access::blobs_events(access))); + let router = Router::builder(endpoint.clone()) + .accept(id_sync::protocol::META_ALPN, meta) + .accept(iroh_blobs::ALPN, blobs) + .spawn(); + lookup.add_endpoint_info(endpoint.addr()); + DestNode { + endpoint, + store, + router, + _docs: docs, + } + } + + #[tokio::test] + async fn send_through_the_handler_copies_the_file_and_retries_safely() { + let lookup = MemoryLookup::new(); + let source_endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .address_lookup(lookup.clone()) + .bind() + .await + .unwrap(); + let source_id = source_endpoint.id(); + let (state, source_store, _docs) = state_on(source_endpoint, "send-t-source").await; + let dest = dest_node(&lookup, source_id, "send-t-destnode").await; + let dest_id = dest.endpoint.id().to_string(); + + // Success: the receipt exists only after the destination + // confirmed, and the destination now names the hash. + let hash = put_named(&source_store, "report.txt", b"hello web send").await; + let response = send(state.clone(), "report.txt", &dest_id, false).await; + assert_eq!(response.status(), StatusCode::OK); + let body = response_json(response).await; + assert_eq!(body["name"], "report.txt"); + assert_eq!(body["dest_name"], "report.txt"); + assert_eq!(body["dest"], dest_id); + assert_eq!(body["hash"], hash.to_string()); + assert_eq!(body["already_present"], false); + assert_eq!( + dest.store + .tags() + .get("report.txt") + .await + .unwrap() + .map(|t| t.hash), + Some(hash) + ); + // The source is untouched: a send is a copy, never a move. + assert_eq!( + source_store + .tags() + .get("report.txt") + .await + .unwrap() + .map(|t| t.hash), + Some(hash) + ); + + // Retry of the same send is idempotent, not a conflict. + let response = send(state.clone(), "report.txt", &dest_id, false).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response_json(response).await["already_present"], true); + + // Conflict refuses by default (409, destination untouched) and + // an explicit replacement archives and lands. + let new_hash = put_named(&source_store, "data.bin", b"new content").await; + let old_hash = put_named(&dest.store, "data.bin", b"old content").await; + let response = send(state.clone(), "data.bin", &dest_id, false).await; + assert_eq!(response.status(), StatusCode::CONFLICT); + assert_eq!( + dest.store + .tags() + .get("data.bin") + .await + .unwrap() + .map(|t| t.hash), + Some(old_hash) + ); + let response = send(state.clone(), "data.bin", &dest_id, true).await; + assert_eq!(response.status(), StatusCode::OK); + let body = response_json(response).await; + assert_eq!(body["replaced"], true); + assert_eq!( + dest.store + .tags() + .get("data.bin") + .await + .unwrap() + .map(|t| t.hash), + Some(new_hash) + ); + + dest.router.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn unallowlisted_destination_denies_the_send() { + let lookup = MemoryLookup::new(); + let source_endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .address_lookup(lookup.clone()) + .bind() + .await + .unwrap(); + let (state, source_store, _docs) = state_on(source_endpoint, "send-t-denied-source").await; + // The destination admits a different writer, not this server. + let other = plain_endpoint().await; + let dest = dest_node(&lookup, other.id(), "send-t-denied-dest").await; + put_named(&source_store, "report.txt", b"not for you").await; + + let response = send(state, "report.txt", &dest.endpoint.id().to_string(), false).await; + assert_eq!(response.status(), StatusCode::BAD_GATEWAY); + assert_eq!( + dest.store + .tags() + .get("report.txt") + .await + .unwrap() + .map(|t| t.hash), + None + ); + + dest.router.shutdown().await.unwrap(); + } +} diff --git a/pkgs/id/crates/id-web/src/templates.rs b/pkgs/id/crates/id-web/src/templates.rs index 14d2d46283..7a6c4dc174 100644 --- a/pkgs/id/crates/id-web/src/templates.rs +++ b/pkgs/id/crates/id-web/src/templates.rs @@ -256,6 +256,8 @@ pub fn render_file_list_content(page: &FileListPage) -> String { html.push_str(""); html.push_str(""); html.push_str(""); + html.push_str(""); + html.push_str(""); html.push_str(""); html.push_str(""); diff --git a/pkgs/id/web/src/file-op-responses.test.ts b/pkgs/id/web/src/file-op-responses.test.ts index 820bfdf817..1d59799a9e 100644 --- a/pkgs/id/web/src/file-op-responses.test.ts +++ b/pkgs/id/web/src/file-op-responses.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from "vitest"; -import { isCopyFileResponse, isNewFileResponse, isRenameFileResponse, isSaveFileResponse } from "./file-op-responses"; +import { + isCopyFileResponse, + isNewFileResponse, + isRenameFileResponse, + isSaveFileResponse, + isSendFileResponse, +} from "./file-op-responses"; // Regression tests for #7837: the /api/save, /api/new, /api/rename and // /api/copy handlers in main.ts shape-trusted their 200 responses via @@ -34,6 +40,34 @@ describe("isSaveFileResponse", () => { }); }); +describe("isSendFileResponse", () => { + const valid = { + name: "report.txt", + dest_name: "report.txt", + dest: "ab".repeat(32), + hash: "abc123", + already_present: false, + replaced: false, + }; + + it("accepts a valid send receipt", () => { + expect(isSendFileResponse(valid)).toBe(true); + expect(isSendFileResponse({ ...valid, already_present: true })).toBe(true); + expect(isSendFileResponse({ ...valid, replaced: true })).toBe(true); + }); + + it("rejects wrong-shape bodies (a failed send must never read as success)", () => { + for (const body of wrongShapes) { + expect(isSendFileResponse(body)).toBe(false); + } + expect(isSendFileResponse({ ...valid, hash: 123 })).toBe(false); + expect(isSendFileResponse({ ...valid, dest: "" })).toBe(false); + expect(isSendFileResponse({ ...valid, already_present: "no" })).toBe(false); + const { replaced: _dropped, ...missingReplaced } = valid; + expect(isSendFileResponse(missingReplaced)).toBe(false); + }); +}); + describe("isNewFileResponse", () => { it("accepts a valid create response", () => { expect(isNewFileResponse({ hash: "abc123", name: "new.md" })).toBe(true); diff --git a/pkgs/id/web/src/file-op-responses.ts b/pkgs/id/web/src/file-op-responses.ts index f37c2110ef..73e4b57db1 100644 --- a/pkgs/id/web/src/file-op-responses.ts +++ b/pkgs/id/web/src/file-op-responses.ts @@ -40,6 +40,15 @@ export interface CopyFileResponse { hash: string; } +export interface SendFileResponse { + name: string; + dest_name: string; + dest: string; + hash: string; + already_present: boolean; + replaced: boolean; +} + const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -73,3 +82,22 @@ export function isRenameFileResponse(value: unknown): value is RenameFileRespons export function isCopyFileResponse(value: unknown): value is CopyFileResponse { return isRecord(value) && isNonEmptyString(value.name) && isNonEmptyString(value.hash); } + +/** + * Guard for POST /api/files/send responses (#5346). A send is reported + * as done only from a well-shaped receipt: the handler answers 200 + * only after the destination confirmed blob completion and name + * registration, and a wrong-shape 200 must never be counted as a + * successful send (the #7837 failure mode, applied to sends). + */ +export function isSendFileResponse(value: unknown): value is SendFileResponse { + return ( + isRecord(value) && + isNonEmptyString(value.name) && + isNonEmptyString(value.dest_name) && + isNonEmptyString(value.dest) && + isNonEmptyString(value.hash) && + typeof value.already_present === "boolean" && + typeof value.replaced === "boolean" + ); +} diff --git a/pkgs/id/web/src/main.ts b/pkgs/id/web/src/main.ts index 9e6d631c55..3c3c2bb987 100644 --- a/pkgs/id/web/src/main.ts +++ b/pkgs/id/web/src/main.ts @@ -23,7 +23,13 @@ import { closeImageBrowser } from "./image-browser"; import { createNavigation } from "./navigation"; import { resolveSaveFilename } from "./save-filename"; import { parseTagsResponse } from "./tags-response"; -import { isCopyFileResponse, isNewFileResponse, isRenameFileResponse, isSaveFileResponse } from "./file-op-responses"; +import { + isCopyFileResponse, + isNewFileResponse, + isRenameFileResponse, + isSaveFileResponse, + isSendFileResponse, +} from "./file-op-responses"; import { isSaveShortcut } from "./save-shortcut"; import { cycleTheme, initTheme, setTheme, type Theme } from "./theme"; @@ -54,6 +60,7 @@ interface IdApp { addTagInline: () => Promise; removeTag: (subject: string, key: string, value: string | null) => Promise; bulkAddTag: () => Promise; + bulkSendToServer: () => Promise; bulkClearSelection: () => void; initBulkSelect: () => void; navHistory: string[]; @@ -980,6 +987,61 @@ async function init(): Promise { // Tags WS will refresh the file list }, + /** + * Send each selected file to another server (#5346). + * + * One POST /api/files/send per selected file: the browser carries + * only the file name and the destination node ID — this server + * performs each transfer itself, server-to-server. A file counts + * as sent only when the response is OK *and* carries a well-shaped + * receipt (the server answers 200 only after the destination + * confirmed the send); every other outcome is reported as failed + * for that file, never as success. + */ + async bulkSendToServer(): Promise { + const destInput = document.getElementById("bulk-send-dest") as HTMLInputElement | null; + if (!destInput) return; + + const dest = destInput.value.trim(); + if (!dest) return; + + const checkboxes = document.querySelectorAll(".file-select:checked") as NodeListOf; + const subjects: string[] = []; + checkboxes.forEach((cb) => { + const name = cb.dataset.name; + if (name) subjects.push(name); + }); + + if (subjects.length === 0) return; + + let successCount = 0; + const failures: string[] = []; + for (const name of subjects) { + try { + const response = await fetch("/api/files/send", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, dest }), + }); + const result: unknown = await response.json().catch(() => null); + if (response.ok && isSendFileResponse(result)) { + successCount++; + } else { + failures.push(name); + console.error("[id] Send failed for", name, result); + } + } catch (err) { + failures.push(name); + console.error("[id] Send error for", name, err); + } + } + + console.log( + `[id] Bulk send: sent ${successCount}/${subjects.length} files to ${dest}` + + (failures.length > 0 ? `; failed: ${failures.join(", ")}` : ""), + ); + }, + /** * Clear all file selection checkboxes on the home page. */