lib.rs
| 1 | //! The HTTP wire contract of filebrowser-ng in one place. |
| 2 | //! |
| 3 | //! Both the server (axum) and the web frontend (wasm `fetch`) import these |
| 4 | //! endpoint paths, query params and serde types, so the two sides cannot |
| 5 | //! drift apart. Serde only — no axum, no wasm dependencies. |
| 6 | |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | |
| 9 | // --------------------------------------------------------------------------- |
| 10 | // Endpoint paths (single source of truth for the route table and the client) |
| 11 | // --------------------------------------------------------------------------- |
| 12 | |
| 13 | pub const AUTH_LOGIN: &str = "/api/auth/login"; |
| 14 | pub const AUTH_LOGOUT: &str = "/api/auth/logout"; |
| 15 | pub const AUTH_ME: &str = "/api/auth/me"; |
| 16 | pub const AUTH_SETUP: &str = "/api/auth/setup"; |
| 17 | /// Change or set the signed-in user's password (`POST`), or remove it |
| 18 | /// (`DELETE`, passkey-only accounts). |
| 19 | pub const AUTH_PASSWORD: &str = "/api/auth/password"; |
| 20 | /// `PUT` the signed-in user's sign-in requirement ([`AuthMode`]). |
| 21 | pub const AUTH_MODE: &str = "/api/auth/mode"; |
| 22 | /// The signed-in user's passkeys: `GET {AUTH_PASSKEYS}` lists them, |
| 23 | /// `DELETE {AUTH_PASSKEYS}/{id}` removes one. |
| 24 | pub const AUTH_PASSKEYS: &str = "/api/auth/passkeys"; |
| 25 | /// Start registering a new passkey (`POST`). Finished at |
| 26 | /// `{AUTH_PASSKEYS_REGISTER}{FINISH_SUFFIX}`. |
| 27 | pub const AUTH_PASSKEYS_REGISTER: &str = "/api/auth/passkeys/register"; |
| 28 | /// Start a passkey sign-in (`POST`, no session needed). Finished at |
| 29 | /// `{AUTH_PASSKEY_LOGIN}{FINISH_SUFFIX}`. |
| 30 | pub const AUTH_PASSKEY_LOGIN: &str = "/api/auth/passkey/login"; |
| 31 | /// The signed-in user's WebDAV app passwords: `GET {AUTH_APP_PASSWORDS}` |
| 32 | /// lists them, `POST` creates one, `DELETE {AUTH_APP_PASSWORDS}/{id}` revokes |
| 33 | /// one. |
| 34 | pub const AUTH_APP_PASSWORDS: &str = "/api/auth/app-passwords"; |
| 35 | /// Second leg of both WebAuthn ceremonies: the browser's answer goes to the |
| 36 | /// begin path plus this suffix. |
| 37 | pub const FINISH_SUFFIX: &str = "/finish"; |
| 38 | /// File operations: `{FILES}/{root_id}` and `{FILES}/{root_id}/{path...}`. |
| 39 | pub const FILES: &str = "/api/files"; |
| 40 | /// Share management (authenticated): `{SHARES}` and `{SHARES}/{id}`. |
| 41 | pub const SHARES: &str = "/api/shares"; |
| 42 | /// Public share resolve (no login): `{SHARE}/{token}`. |
| 43 | pub const SHARE: &str = "/api/share"; |
| 44 | /// Suffix on `{SHARE}/{token}`: submit the password of a protected share. |
| 45 | pub const SHARE_UNLOCK_SUFFIX: &str = "/unlock"; |
| 46 | /// `GET /api/search` — name and/or content search, streamed as SSE. |
| 47 | pub const SEARCH: &str = "/api/search"; |
| 48 | |
| 49 | /// WebDAV mount of the signed-in user's roots: `{DAV}` and `{DAV}/{path...}`. |
| 50 | pub const DAV: &str = "/dav"; |
| 51 | /// WebDAV mount of one public share: `{DAV_SHARE}/{token}/{path...}`. |
| 52 | /// |
| 53 | /// A separate top-level path, not a segment under [`DAV`]: there, the first |
| 54 | /// segment is a root's display name, which a reserved word could collide with. |
| 55 | pub const DAV_SHARE: &str = "/dav-share"; |
| 56 | |
| 57 | /// Admin user management: `{ADMIN_USERS}` and `{ADMIN_USERS}/{id}`. |
| 58 | pub const ADMIN_USERS: &str = "/api/admin/users"; |
| 59 | /// Admin view of every share on the server: `{ADMIN_SHARES}` and |
| 60 | /// `{ADMIN_SHARES}/{id}`. [`SHARES`] is the same data scoped to the caller. |
| 61 | pub const ADMIN_SHARES: &str = "/api/admin/shares"; |
| 62 | pub const ADMIN_SETTINGS: &str = "/api/admin/settings"; |
| 63 | /// Pseudo root id every signed-in admin has on the files API: the whole |
| 64 | /// server root, read-only (the admin folder picker browses it). Real root |
| 65 | /// ids are positive database ids. Not listed in `/me`. |
| 66 | pub const ADMIN_ROOT: i64 = -1; |
| 67 | |
| 68 | // --------------------------------------------------------------------------- |
| 69 | // Query params |
| 70 | // --------------------------------------------------------------------------- |
| 71 | |
| 72 | /// `?action=...` on file URLs; without it the route lists the directory. |
| 73 | pub const P_ACTION: &str = "action"; |
| 74 | pub const ACTION_DOWNLOAD: &str = "download"; |
| 75 | pub const ACTION_PREVIEW: &str = "preview"; |
| 76 | pub const ACTION_CONTENT: &str = "content"; |
| 77 | pub const ACTION_THUMB: &str = "thumb"; |
| 78 | /// `POST {FILES}/...?action=mkdir` — create a folder. Explicit, because the |
| 79 | /// POST route also carries uploads and mutations. |
| 80 | pub const ACTION_MKDIR: &str = "mkdir"; |
| 81 | /// `POST {FILES}/...?action=create-file` — create an empty file. Explicit |
| 82 | /// like `mkdir`, for the same reason. |
| 83 | pub const ACTION_CREATE_FILE: &str = "create-file"; |
| 84 | /// `POST {FILES}/...?action=exists` with an [`ExistsReq`] body — read-only |
| 85 | /// pre-check for an upload: which of the given targets already exist. |
| 86 | pub const ACTION_EXISTS: &str = "exists"; |
| 87 | /// `?format=...` for folder downloads (values: see `server::archive::ArchiveFormat`). |
| 88 | pub const P_FORMAT: &str = "format"; |
| 89 | /// `?share=<token>` — authenticate file calls with a public share token. |
| 90 | pub const P_SHARE: &str = "share"; |
| 91 | /// Search query text (`GET {SEARCH}`). |
| 92 | pub const P_Q: &str = "q"; |
| 93 | /// Which index to search: `name`, `content` or `both`. |
| 94 | pub const P_SCOPE: &str = "scope"; |
| 95 | /// Root id to search; omitted = the caller's first root. |
| 96 | pub const P_ROOT: &str = "root"; |
| 97 | /// Folder inside the root to start a search in (relative to the root); |
| 98 | /// omitted or empty = the whole root. |
| 99 | pub const P_PATH: &str = "path"; |
| 100 | /// `?overwrite=true|1` on mutations and uploads. |
| 101 | pub const P_OVERWRITE: &str = "overwrite"; |
| 102 | /// Listing order ([`SortKey`]); omitted = by name. |
| 103 | pub const P_SORT: &str = "sort"; |
| 104 | /// `?desc=true` reverses the listing order. Folders still come first. |
| 105 | pub const P_DESC: &str = "desc"; |
| 106 | /// First listing entry to return, in the sorted order. |
| 107 | pub const P_OFFSET: &str = "offset"; |
| 108 | /// Listing entries to return, capped at [`MAX_LIST_ENTRIES`]; omitted = the cap. |
| 109 | pub const P_LIMIT: &str = "limit"; |
| 110 | /// `?dirs=true` lists only the subfolders (the folder picker). |
| 111 | pub const P_DIRS: &str = "dirs"; |
| 112 | /// `?around=name` returns the page that holds this entry, instead of the |
| 113 | /// one at the offset. A missing name falls back to the offset. |
| 114 | pub const P_AROUND: &str = "around"; |
| 115 | |
| 116 | // --------------------------------------------------------------------------- |
| 117 | // Wire enums |
| 118 | // --------------------------------------------------------------------------- |
| 119 | |
| 120 | /// Access mode of a root or a share. |
| 121 | /// |
| 122 | /// The serde names are also the values stored in the SQLite `mode` columns, |
| 123 | /// so renaming a variant would break existing databases. The round-trip test |
| 124 | /// below pins them. |
| 125 | #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] |
| 126 | #[serde(rename_all = "lowercase")] |
| 127 | pub enum Mode { |
| 128 | Rw, |
| 129 | Ro, |
| 130 | } |
| 131 | |
| 132 | impl Mode { |
| 133 | /// The only question callers ask: may this root be written to? |
| 134 | pub fn is_writable(self) -> bool { |
| 135 | matches!(self, Mode::Rw) |
| 136 | } |
| 137 | |
| 138 | /// The wire/database spelling, for `<select>` values and SQL params. |
| 139 | pub fn as_str(self) -> &'static str { |
| 140 | match self { |
| 141 | Mode::Rw => "rw", |
| 142 | Mode::Ro => "ro", |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Parse the wire spelling. `None` for anything else. |
| 147 | pub fn from_wire(s: &str) -> Option<Self> { |
| 148 | match s { |
| 149 | "rw" => Some(Mode::Rw), |
| 150 | "ro" => Some(Mode::Ro), |
| 151 | _ => None, |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Which mutation [`Mutation`] asks for. |
| 157 | #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] |
| 158 | #[serde(rename_all = "lowercase")] |
| 159 | pub enum Op { |
| 160 | Rename, |
| 161 | Move, |
| 162 | Copy, |
| 163 | } |
| 164 | |
| 165 | /// What a listing is ordered by ([`P_SORT`]). Folders always sort before |
| 166 | /// files, so a size or date order does not scatter them through the listing. |
| 167 | #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default)] |
| 168 | #[serde(rename_all = "lowercase")] |
| 169 | pub enum SortKey { |
| 170 | #[default] |
| 171 | Name, |
| 172 | Size, |
| 173 | Modified, |
| 174 | } |
| 175 | |
| 176 | impl SortKey { |
| 177 | pub fn as_str(self) -> &'static str { |
| 178 | match self { |
| 179 | SortKey::Name => "name", |
| 180 | SortKey::Size => "size", |
| 181 | SortKey::Modified => "modified", |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | pub fn parse(s: &str) -> Option<Self> { |
| 186 | match s { |
| 187 | "name" => Some(SortKey::Name), |
| 188 | "size" => Some(SortKey::Size), |
| 189 | "modified" => Some(SortKey::Modified), |
| 190 | _ => None, |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | // --------------------------------------------------------------------------- |
| 196 | // Request bodies (client → server) |
| 197 | // --------------------------------------------------------------------------- |
| 198 | |
| 199 | #[derive(Serialize, Deserialize)] |
| 200 | pub struct Credentials { |
| 201 | pub name: String, |
| 202 | pub password: String, |
| 203 | } |
| 204 | |
| 205 | /// Rename / move / copy (one body for all file mutations). |
| 206 | #[derive(Serialize, Deserialize)] |
| 207 | pub struct Mutation { |
| 208 | pub op: Op, |
| 209 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 210 | pub new_name: Option<String>, |
| 211 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 212 | pub dst_root_id: Option<i64>, |
| 213 | /// Destination directory, relative to `dst_root_id`. |
| 214 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 215 | pub dst: Option<String>, |
| 216 | #[serde(default)] |
| 217 | pub overwrite: bool, |
| 218 | } |
| 219 | |
| 220 | /// A user folder: path relative to the server root + access mode. |
| 221 | #[derive(Serialize, Deserialize)] |
| 222 | pub struct Root { |
| 223 | /// Path relative to the server root; "." means the whole root. |
| 224 | pub path: String, |
| 225 | #[serde(default = "default_rw")] |
| 226 | pub mode: Mode, |
| 227 | } |
| 228 | |
| 229 | fn default_rw() -> Mode { |
| 230 | Mode::Rw |
| 231 | } |
| 232 | |
| 233 | #[derive(Serialize, Deserialize)] |
| 234 | pub struct CreateUser { |
| 235 | pub name: String, |
| 236 | pub password: String, |
| 237 | #[serde(default)] |
| 238 | pub is_admin: bool, |
| 239 | #[serde(default)] |
| 240 | pub roots: Vec<Root>, |
| 241 | } |
| 242 | |
| 243 | #[derive(Serialize, Deserialize)] |
| 244 | pub struct UpdateUser { |
| 245 | /// Setting one is also the recovery path for a locked-out account: it |
| 246 | /// deletes every passkey and puts the account back on |
| 247 | /// [`AuthMode::Either`], leaving the new password as the one way in. |
| 248 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 249 | pub password: Option<String>, |
| 250 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 251 | pub is_admin: Option<bool>, |
| 252 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 253 | pub active: Option<bool>, |
| 254 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 255 | pub roots: Option<Vec<Root>>, |
| 256 | } |
| 257 | |
| 258 | /// Server settings (GET/PUT `{ADMIN_SETTINGS}`). |
| 259 | #[derive(Serialize, Deserialize, Clone)] |
| 260 | pub struct Settings { |
| 261 | pub allow_writable_shares: bool, |
| 262 | /// Folders left out of every search, as paths relative to the server |
| 263 | /// root. A path covers everything beneath it. |
| 264 | #[serde(default)] |
| 265 | pub search_excludes: Vec<String>, |
| 266 | } |
| 267 | |
| 268 | #[derive(Serialize, Deserialize)] |
| 269 | pub struct CreateShare { |
| 270 | pub root_id: i64, |
| 271 | /// Item path relative to the root ("" or "." for the root itself). |
| 272 | pub path: String, |
| 273 | #[serde(default)] |
| 274 | pub writable: bool, |
| 275 | /// Absolute expiry as RFC 3339; absent = never. |
| 276 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 277 | pub expires_at: Option<String>, |
| 278 | /// Password the visitor must enter before the share opens; absent = none. |
| 279 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 280 | pub password: Option<String>, |
| 281 | } |
| 282 | |
| 283 | /// POST `{SHARE}/{token}/unlock` — the password for a protected share. |
| 284 | #[derive(Serialize, Deserialize)] |
| 285 | pub struct UnlockShare { |
| 286 | pub password: String, |
| 287 | } |
| 288 | |
| 289 | // --------------------------------------------------------------------------- |
| 290 | // Responses (server → client) |
| 291 | // --------------------------------------------------------------------------- |
| 292 | |
| 293 | /// What a listing entry actually is, decided by the server from the file's |
| 294 | /// leading bytes (magic numbers via `infer`, plus a text/binary heuristic) — |
| 295 | /// not from its name. Drives the icon and the preview the client offers. |
| 296 | /// |
| 297 | /// Deliberately coarse: this answers "which viewer opens this", not "what |
| 298 | /// exact format is it". Syntax highlighting still keys off the extension, |
| 299 | /// because `.h` is C or C++ and no amount of sniffing decides that. |
| 300 | #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] |
| 301 | #[serde(rename_all = "lowercase")] |
| 302 | pub enum FileKind { |
| 303 | Dir, |
| 304 | Image, |
| 305 | Video, |
| 306 | Audio, |
| 307 | Pdf, |
| 308 | Archive, |
| 309 | /// Anything that decodes as text: source code, markup, config, plain text. |
| 310 | Text, |
| 311 | /// Recognized-but-not-viewable, or undecodable bytes. |
| 312 | Binary, |
| 313 | } |
| 314 | |
| 315 | #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] |
| 316 | pub struct Entry { |
| 317 | pub name: String, |
| 318 | pub is_dir: bool, |
| 319 | pub size: u64, |
| 320 | /// RFC 3339 UTC modification time. |
| 321 | pub mtime: String, |
| 322 | /// Content-sniffed kind (see [`FileKind`]). |
| 323 | pub kind: FileKind, |
| 324 | } |
| 325 | |
| 326 | /// One page of a folder listing. |
| 327 | #[derive(Serialize, Deserialize)] |
| 328 | pub struct FilesResp { |
| 329 | pub entries: Vec<Entry>, |
| 330 | /// Entries in the whole folder, across all pages. |
| 331 | pub total: usize, |
| 332 | /// Position of `entries[0]` in the sorted folder. An offset past the end |
| 333 | /// comes back as the start of the last page. |
| 334 | pub offset: usize, |
| 335 | } |
| 336 | |
| 337 | /// Cap on entries in one listing page. |
| 338 | pub const MAX_LIST_ENTRIES: usize = 10_000; |
| 339 | |
| 340 | /// One streamed search result. Each is sent as one SSE event |
| 341 | /// (`data: <json>`), in the order found; the `done` event always ends the |
| 342 | /// stream. |
| 343 | #[derive(Serialize, Deserialize, Clone)] |
| 344 | #[serde(tag = "type", rename_all = "snake_case")] |
| 345 | pub enum SearchEvent { |
| 346 | /// A file or folder whose name matched (scope `name`/`both`). |
| 347 | File { |
| 348 | root_id: i64, |
| 349 | /// Path relative to the root, `/`-separated. |
| 350 | path: String, |
| 351 | size: u64, |
| 352 | is_dir: bool, |
| 353 | /// Sniffed the same way as a directory listing's, so the client can |
| 354 | /// pick an icon and a viewer without a second guess at the name. |
| 355 | kind: FileKind, |
| 356 | }, |
| 357 | /// One matching line (scope `content`/`both`). `path` is relative to the |
| 358 | /// root; `text` is the matched line, truncated to a fixed length. |
| 359 | Match { |
| 360 | root_id: i64, |
| 361 | path: String, |
| 362 | line: u64, |
| 363 | text: String, |
| 364 | }, |
| 365 | /// Stream finished. `stopped` is true when the client aborted before the |
| 366 | /// search completed. |
| 367 | Done { |
| 368 | stopped: bool, |
| 369 | /// Files examined (walked) before the stream ended. |
| 370 | scanned: usize, |
| 371 | /// Files skipped for content search (over the size cap). |
| 372 | skipped: usize, |
| 373 | elapsed_ms: u64, |
| 374 | }, |
| 375 | } |
| 376 | |
| 377 | #[derive(Serialize, Deserialize, Clone, PartialEq)] |
| 378 | pub struct UserInfo { |
| 379 | pub id: i64, |
| 380 | pub name: String, |
| 381 | pub is_admin: bool, |
| 382 | /// Profile setting: single click opens entries (off = click selects, |
| 383 | /// double click opens). |
| 384 | pub single_click_open: bool, |
| 385 | /// Profile setting: show image and video thumbnails in the grid. |
| 386 | pub thumbnails: bool, |
| 387 | /// Preferred UI language tag ("en", "de", "fr"); None = follow the |
| 388 | /// browser. |
| 389 | pub language: Option<String>, |
| 390 | /// Profile setting: the root the UI opens on page load and on the home |
| 391 | /// link. Always one of `Me::roots` (the server drops a stale id), or |
| 392 | /// None for the root picker. |
| 393 | pub default_root_id: Option<i64>, |
| 394 | /// What this account needs to sign in. |
| 395 | pub auth_mode: AuthMode, |
| 396 | /// Whether a password is set at all. False means passkeys only. |
| 397 | pub has_password: bool, |
| 398 | } |
| 399 | |
| 400 | #[derive(Serialize, Deserialize, Clone)] |
| 401 | pub struct RootInfo { |
| 402 | pub id: i64, |
| 403 | pub name: String, |
| 404 | pub path: String, |
| 405 | pub mode: Mode, |
| 406 | } |
| 407 | |
| 408 | /// GET `{AUTH_ME}`. |
| 409 | #[derive(Serialize, Deserialize, Clone)] |
| 410 | pub struct Me { |
| 411 | /// True while no users exist yet (first-boot setup). |
| 412 | pub first_boot: bool, |
| 413 | /// None on first boot. |
| 414 | pub user: Option<UserInfo>, |
| 415 | pub roots: Vec<RootInfo>, |
| 416 | pub allow_writable_shares: bool, |
| 417 | /// Whether the server can make thumbnails at all (`--cache` is set). |
| 418 | /// The profile setting is only offered when this is true. |
| 419 | pub thumbnails_available: bool, |
| 420 | /// `--public-url`, if set. The UI builds share links from it instead of |
| 421 | /// the page origin. |
| 422 | pub public_url: Option<String>, |
| 423 | } |
| 424 | |
| 425 | /// GET/POST `{SHARES}`, GET `{SHARE}/{token}`. |
| 426 | #[derive(Serialize, Deserialize, Clone)] |
| 427 | pub struct ShareInfo { |
| 428 | /// Also the share's synthetic root id in file API calls. |
| 429 | pub id: i64, |
| 430 | pub token: String, |
| 431 | /// Display name (file/folder name, or the root's name for "."). |
| 432 | pub name: String, |
| 433 | pub is_file: bool, |
| 434 | pub writable: bool, |
| 435 | /// Path relative to the server root. |
| 436 | pub target: String, |
| 437 | /// RFC 3339 UTC creation time. |
| 438 | pub created_at: String, |
| 439 | /// RFC 3339 UTC expiry; None = never. |
| 440 | pub expires_at: Option<String>, |
| 441 | /// The file's kind for file shares (None for folder shares, and when |
| 442 | /// not sniffed — the public resolve endpoint fills it in). |
| 443 | pub kind: Option<FileKind>, |
| 444 | /// Whether the share asks for a password. Never the password itself. |
| 445 | pub has_password: bool, |
| 446 | } |
| 447 | |
| 448 | /// One share plus who owns it: GET `{ADMIN_SHARES}`. |
| 449 | /// |
| 450 | /// Admin-only: it carries the full [`ShareInfo::token`], and a token is access. |
| 451 | /// Kept separate from [`ShareInfo`] because the public resolve route answers |
| 452 | /// with a `ShareInfo` to anonymous visitors. |
| 453 | #[derive(Serialize, Deserialize, Clone)] |
| 454 | pub struct AdminShare { |
| 455 | #[serde(flatten)] |
| 456 | pub share: ShareInfo, |
| 457 | pub creator_id: i64, |
| 458 | pub creator_name: String, |
| 459 | /// Whether the creator's account can still sign in. Deactivating an account |
| 460 | /// does not revoke its shares, so `false` marks a live link its owner can no |
| 461 | /// longer manage. |
| 462 | pub creator_active: bool, |
| 463 | } |
| 464 | |
| 465 | /// GET/POST `{ADMIN_USERS}`, PUT `{ADMIN_USERS}/{id}`. |
| 466 | #[derive(Serialize, Deserialize, Clone)] |
| 467 | pub struct AdminUser { |
| 468 | pub id: i64, |
| 469 | pub name: String, |
| 470 | pub is_admin: bool, |
| 471 | pub active: bool, |
| 472 | pub roots: Vec<RootInfo>, |
| 473 | } |
| 474 | |
| 475 | /// Acknowledges a successful mutation. Carries nothing: the 2xx status is |
| 476 | /// the acknowledgement, so the body is the empty object. |
| 477 | #[derive(Serialize, Deserialize)] |
| 478 | pub struct OkResp {} |
| 479 | |
| 480 | /// `POST ...?action=exists` body: upload targets relative to the request |
| 481 | /// directory (may contain subfolders, like upload part names). |
| 482 | #[derive(Serialize, Deserialize)] |
| 483 | pub struct ExistsReq { |
| 484 | pub paths: Vec<String>, |
| 485 | } |
| 486 | |
| 487 | /// One existing upload target. |
| 488 | #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] |
| 489 | pub struct Existing { |
| 490 | pub path: String, |
| 491 | pub is_dir: bool, |
| 492 | } |
| 493 | |
| 494 | /// `POST ...?action=exists` response: the subset of the requested paths |
| 495 | /// that exist, in request order. |
| 496 | #[derive(Serialize, Deserialize)] |
| 497 | pub struct ExistsResp { |
| 498 | pub existing: Vec<Existing>, |
| 499 | } |
| 500 | |
| 501 | /// PUT `?action=content` (editor save): the file's new mtime (unix seconds). |
| 502 | #[derive(Serialize, Deserialize)] |
| 503 | pub struct SaveResp { |
| 504 | pub mtime: i64, |
| 505 | } |
| 506 | |
| 507 | #[cfg(test)] |
| 508 | mod tests { |
| 509 | use super::*; |
| 510 | |
| 511 | /// The serde spellings are the database values too, so they are pinned. |
| 512 | #[test] |
| 513 | fn mode_wire_format_is_rw_ro() { |
| 514 | assert_eq!(serde_json::to_string(&Mode::Rw).unwrap(), "\"rw\""); |
| 515 | assert_eq!(serde_json::to_string(&Mode::Ro).unwrap(), "\"ro\""); |
| 516 | for m in [Mode::Rw, Mode::Ro] { |
| 517 | let s = serde_json::to_string(&m).unwrap(); |
| 518 | assert_eq!(serde_json::from_str::<Mode>(&s).unwrap(), m); |
| 519 | // `as_str`/`from_wire` must agree with serde. |
| 520 | assert_eq!(s, format!("\"{}\"", m.as_str())); |
| 521 | assert_eq!(Mode::from_wire(m.as_str()), Some(m)); |
| 522 | } |
| 523 | assert_eq!(Mode::from_wire("both"), None); |
| 524 | assert!(serde_json::from_str::<Mode>("\"both\"").is_err()); |
| 525 | assert!(Mode::Rw.is_writable()); |
| 526 | assert!(!Mode::Ro.is_writable()); |
| 527 | } |
| 528 | |
| 529 | #[test] |
| 530 | fn op_wire_format() { |
| 531 | assert_eq!(serde_json::to_string(&Op::Rename).unwrap(), "\"rename\""); |
| 532 | assert_eq!(serde_json::to_string(&Op::Move).unwrap(), "\"move\""); |
| 533 | assert_eq!(serde_json::to_string(&Op::Copy).unwrap(), "\"copy\""); |
| 534 | for op in [Op::Rename, Op::Move, Op::Copy] { |
| 535 | let s = serde_json::to_string(&op).unwrap(); |
| 536 | assert_eq!(serde_json::from_str::<Op>(&s).unwrap(), op); |
| 537 | } |
| 538 | assert!(serde_json::from_str::<Op>("\"explode\"").is_err()); |
| 539 | } |
| 540 | |
| 541 | #[test] |
| 542 | fn mutation_round_trip_skips_absent_fields() { |
| 543 | let m = Mutation { |
| 544 | op: Op::Move, |
| 545 | new_name: None, |
| 546 | dst_root_id: Some(3), |
| 547 | dst: Some("docs".into()), |
| 548 | overwrite: true, |
| 549 | }; |
| 550 | let s = serde_json::to_string(&m).unwrap(); |
| 551 | assert!(!s.contains("new_name")); |
| 552 | let back: Mutation = serde_json::from_str(&s).unwrap(); |
| 553 | assert_eq!(back.dst_root_id, Some(3)); |
| 554 | assert_eq!(back.op, Op::Move); |
| 555 | } |
| 556 | |
| 557 | #[test] |
| 558 | fn mutation_defaults_missing_fields() { |
| 559 | let m: Mutation = serde_json::from_str(r#"{"op":"rename","new_name":"a.txt"}"#).unwrap(); |
| 560 | assert!(!m.overwrite); |
| 561 | assert_eq!(m.dst, None); |
| 562 | } |
| 563 | |
| 564 | #[test] |
| 565 | fn root_defaults_mode_to_rw() { |
| 566 | let r: Root = serde_json::from_str(r#"{"path":"docs"}"#).unwrap(); |
| 567 | assert_eq!(r.mode, Mode::Rw); |
| 568 | } |
| 569 | |
| 570 | #[test] |
| 571 | fn me_round_trip() { |
| 572 | let me = Me { |
| 573 | first_boot: false, |
| 574 | user: Some(UserInfo { |
| 575 | id: 1, |
| 576 | name: "admin".into(), |
| 577 | is_admin: true, |
| 578 | single_click_open: false, |
| 579 | thumbnails: true, |
| 580 | language: None, |
| 581 | default_root_id: None, |
| 582 | auth_mode: AuthMode::Either, |
| 583 | has_password: true, |
| 584 | }), |
| 585 | roots: vec![RootInfo { |
| 586 | id: 1, |
| 587 | name: "root".into(), |
| 588 | path: ".".into(), |
| 589 | mode: Mode::Rw, |
| 590 | }], |
| 591 | allow_writable_shares: false, |
| 592 | thumbnails_available: true, |
| 593 | public_url: None, |
| 594 | }; |
| 595 | let s = serde_json::to_string(&me).unwrap(); |
| 596 | let back: Me = serde_json::from_str(&s).unwrap(); |
| 597 | assert_eq!(back.roots.len(), 1); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | // --------------------------------------------------------------------------- |
| 602 | // Sign-in methods: password, passkeys, and how they combine |
| 603 | // --------------------------------------------------------------------------- |
| 604 | |
| 605 | /// What an account needs to sign in. |
| 606 | /// |
| 607 | /// Not a "2FA on/off" flag: [`AuthMode::Either`] with no password is a |
| 608 | /// passkey-only account, which is still two factors when the authenticator |
| 609 | /// does user verification (the server always asks for it). |
| 610 | #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 611 | #[serde(rename_all = "lowercase")] |
| 612 | pub enum AuthMode { |
| 613 | /// Password *or* passkey. Either one alone signs the user in. |
| 614 | #[default] |
| 615 | Either, |
| 616 | /// Password *and* passkey. Both legs must pass, in either order. |
| 617 | Both, |
| 618 | } |
| 619 | |
| 620 | impl AuthMode { |
| 621 | pub fn as_str(self) -> &'static str { |
| 622 | match self { |
| 623 | AuthMode::Either => "either", |
| 624 | AuthMode::Both => "both", |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | pub fn from_wire(s: &str) -> Option<Self> { |
| 629 | match s { |
| 630 | "either" => Some(AuthMode::Either), |
| 631 | "both" => Some(AuthMode::Both), |
| 632 | _ => None, |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | /// One registered passkey, as shown in profile settings. Never carries key |
| 638 | /// material. |
| 639 | #[derive(Serialize, Deserialize, Clone)] |
| 640 | pub struct PasskeyInfo { |
| 641 | pub id: i64, |
| 642 | /// User-chosen label ("YubiKey", "Work laptop"). |
| 643 | pub name: String, |
| 644 | /// RFC 3339 UTC. |
| 645 | pub created_at: String, |
| 646 | pub last_used_at: Option<String>, |
| 647 | /// Whether the browser reported this credential as discoverable, so it |
| 648 | /// can sign in without the account name. `None` when the browser did not |
| 649 | /// say — the `credProps` extension is optional and unsigned, so absence |
| 650 | /// means "unknown", never "no". |
| 651 | pub discoverable: Option<bool>, |
| 652 | } |
| 653 | |
| 654 | /// One app password, as shown in profile settings. |
| 655 | /// |
| 656 | /// WebDAV-only: it never signs in to the web UI. Never carries the secret, |
| 657 | /// which exists only in [`NewAppPassword`]. |
| 658 | #[derive(Serialize, Deserialize, Clone)] |
| 659 | pub struct AppPasswordInfo { |
| 660 | pub id: i64, |
| 661 | /// User-chosen label ("Laptop mount", "phone"). |
| 662 | pub name: String, |
| 663 | /// RFC 3339 UTC. |
| 664 | pub created_at: String, |
| 665 | /// Only tracked to the hour. |
| 666 | pub last_used_at: Option<String>, |
| 667 | } |
| 668 | |
| 669 | /// `POST {AUTH_APP_PASSWORDS}`. |
| 670 | #[derive(Serialize, Deserialize)] |
| 671 | pub struct CreateAppPassword { |
| 672 | pub name: String, |
| 673 | } |
| 674 | |
| 675 | /// The answer to `POST {AUTH_APP_PASSWORDS}`. |
| 676 | /// |
| 677 | /// The only time `secret` is readable. The server keeps a hash of it. |
| 678 | #[derive(Serialize, Deserialize)] |
| 679 | pub struct NewAppPassword { |
| 680 | #[serde(flatten)] |
| 681 | pub info: AppPasswordInfo, |
| 682 | pub secret: String, |
| 683 | } |
| 684 | |
| 685 | /// `POST {AUTH_PASSWORD}` — set or change the password. |
| 686 | /// |
| 687 | /// No current password to confirm: a passkey-only account has none to give. |
| 688 | /// The session is the gate, and the server drops the account's other |
| 689 | /// sessions on every change. |
| 690 | #[derive(Serialize, Deserialize)] |
| 691 | pub struct ChangePassword { |
| 692 | pub new_password: String, |
| 693 | } |
| 694 | |
| 695 | /// `PUT {AUTH_MODE}`. |
| 696 | #[derive(Serialize, Deserialize)] |
| 697 | pub struct SetAuthMode { |
| 698 | pub mode: AuthMode, |
| 699 | } |
| 700 | |
| 701 | /// A WebAuthn challenge on its way to the browser. |
| 702 | /// |
| 703 | /// `options` is the raw JSON the browser's `parseCreationOptionsFromJSON` / |
| 704 | /// `parseRequestOptionsFromJSON` expects, carried as a string rather than a |
| 705 | /// nested object. Neither side has to re-parse it: the server serializes the |
| 706 | /// `webauthn-rs` type straight into it, and the client hands it to |
| 707 | /// `JSON.parse` in the browser shim. |
| 708 | #[derive(Serialize, Deserialize)] |
| 709 | pub struct PasskeyChallenge { |
| 710 | /// Opaque handle for the server-side ceremony state. Echoed back on |
| 711 | /// finish. Not a credential, and useless on its own. |
| 712 | pub state_id: String, |
| 713 | pub options: String, |
| 714 | } |
| 715 | |
| 716 | /// `POST {AUTH_PASSKEYS_REGISTER}{FINISH_SUFFIX}`. |
| 717 | #[derive(Serialize, Deserialize)] |
| 718 | pub struct PasskeyRegisterFinish { |
| 719 | pub state_id: String, |
| 720 | /// Label for the new passkey. |
| 721 | pub name: String, |
| 722 | /// The browser's `PublicKeyCredential.toJSON()` output, verbatim. |
| 723 | pub credential: String, |
| 724 | } |
| 725 | |
| 726 | /// `POST {AUTH_PASSKEY_LOGIN}` — begin a passkey sign-in. |
| 727 | #[derive(Serialize, Deserialize)] |
| 728 | pub struct PasskeyLoginBegin { |
| 729 | /// Account name, when the user typed one. Without it the server issues a |
| 730 | /// discoverable challenge, which only finds passkeys the authenticator |
| 731 | /// stores itself. |
| 732 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 733 | pub name: Option<String>, |
| 734 | /// Ask for a conditional-mediation (autofill) challenge instead of a |
| 735 | /// modal one. |
| 736 | #[serde(default)] |
| 737 | pub conditional: bool, |
| 738 | } |
| 739 | |
| 740 | /// `POST {AUTH_PASSKEY_LOGIN}{FINISH_SUFFIX}`. |
| 741 | #[derive(Serialize, Deserialize)] |
| 742 | pub struct PasskeyLoginFinish { |
| 743 | pub state_id: String, |
| 744 | pub credential: String, |
| 745 | } |
| 746 | |
| 747 | /// `POST {AUTH_LOGIN}` — the password leg of a sign-in. |
| 748 | #[derive(Serialize, Deserialize)] |
| 749 | pub struct LoginReq { |
| 750 | /// Omitted only when `state_id` names a half-finished sign-in, which |
| 751 | /// already knows who the user is. |
| 752 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 753 | pub name: Option<String>, |
| 754 | pub password: String, |
| 755 | /// Handle from a passkey leg that still needs a password (an |
| 756 | /// [`AuthMode::Both`] account signing in passkey-first). |
| 757 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 758 | pub state_id: Option<String>, |
| 759 | } |
| 760 | |
| 761 | /// The answer to either sign-in leg. |
| 762 | /// |
| 763 | /// Exactly one of the three shapes: signed in, needs a passkey next, or needs |
| 764 | /// a password next. The two "needs" cases are how [`AuthMode::Both`] works, |
| 765 | /// and which one appears depends only on which leg the user started with. |
| 766 | #[derive(Serialize, Deserialize, Default)] |
| 767 | pub struct LoginResp { |
| 768 | /// True when the session cookie is set and the user is in. |
| 769 | pub ok: bool, |
| 770 | /// Present when this leg passed but a passkey is still required. |
| 771 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 772 | pub passkey_challenge: Option<PasskeyChallenge>, |
| 773 | /// Present when this leg passed but the password is still required. |
| 774 | /// Carries the account name, so the form can show whose password it |
| 775 | /// wants, and the handle to send back with it. |
| 776 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 777 | pub password_required: Option<PasswordStep>, |
| 778 | } |
| 779 | |
| 780 | #[derive(Serialize, Deserialize, Clone)] |
| 781 | pub struct PasswordStep { |
| 782 | pub name: String, |
| 783 | pub state_id: String, |
| 784 | } |
| 785 |