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