# bookclerkd::embedded

The host embedded in a desktop window, with no listener.

[`EmbeddedHost::start`](#embeddedhoststart) runs the same host `bookclerkd` runs (control
plane, plugin deployments, jobs, events, scheduler, library links) but
binds no socket: not `daemon.listen`, not the node API's TLS listener.
The window's webview loads the SPA over its own custom scheme, and the
shell passes each request to [`EmbeddedHost::handle`](#embeddedhosthandle), which calls the
router in-process.

**Who the caller is.** The window belongs to the person signed in to this
computer's OS account (see `docs/adr/desktop-window-identity.md`). Until
the library has an active Owner (first run, or a computer that is only a
clerk of another library) every request is the operator: the host adds
the current operator token as `Authorization: Bearer`, read again for
every request so a rotation applies at once. After that the window is a
patron: the one whose portal session this branch keeps sealed in its
own database, which the host renews at every launch, or nobody until
they sign in on the app's own sign-in screen. The host keeps that patron's session cookies in a
[`session::WindowJar`](/docs/internals/crates/bookclerkd/embedded/session/index.md#windowjar) and adds them to each request; an elevation's
operator session lands there too, so elevation, impersonation and
sign-out work as on the web. Whatever the page sent as cookies,
`Authorization`, `Origin`, `Referer` or forwarding headers is dropped
first, and `Set-Cookie` never reaches the page, so the page holds no
credential of its own. With `daemon.auth.enabled = false` nothing is
added.

**The kept session.** A sign-in in the window (a response that sets the
patron's portal session while no elevation is active) seals the session
for the next launch; creating the library's first Owner in the window
signs the window in as that Owner; signing out forgets it. Elevating,
impersonating and ending either never touch it. The router sees every
request as coming from [`EMBEDDED_ORIGIN`](/docs/internals/crates/bookclerk_window_policy/index.md#embedded_origin), a loopback origin, so a join
or a library card sign-in asks the library to send the window back there.

**Other pages.** Because the token is added here, a page from anywhere
else must not be able to reach the scheme: a request whose `Origin` is
not one of [`APP_ORIGINS`](/docs/internals/crates/bookclerk_window_policy/index.md#app_origins) (or, for a write, whose `Referer` is from
elsewhere) is refused with `403` before routing.

**Leaving the app.** The window shows only app pages, with one exception:
joining a library, or signing in to one with a library card, signs the
person in on the library's own site. From a successful
`POST /api/config/join/start` or `POST /api/config/clerk/start` until the
library sends the window back (or the sign-in expires),
[`EmbeddedHost::navigation`](#embeddedhostnavigation) lets the window open `https` pages; the
library's return to `http://localhost/join/callback` or
`http://localhost/clerk/callback` is handed back to the app scheme.

**What the window cannot reach.** The request carries no peer address,
so routes that admit only a direct loopback connection (the tray
handoff) and the node API's transport policy refuse it. The node API
(`/api/node/...`) is for other nodes over TLS and is refused here before
routing. The live socket (`/api/live`) needs a WebSocket, which a custom
scheme cannot carry; it is refused here. The window hears the same
frames from [`EmbeddedHost::live`](#embeddedhostlive) instead, which the shell forwards to
the page over its own channel.

**Responses** are collected whole, up to [`MAX_RESPONSE_BYTES`](#max_response_bytes) and
[`RESPONSE_TIMEOUT`](#response_timeout); a custom scheme cannot stream.

| Item | Kind | Summary |
| --- | --- | --- |
| [`EmbeddedOptions`](#embeddedoptions) | struct | Where the embedded host reads its files and configuration, as `bookclerkd`'s `--bookclerk-files` and `--config` do. |
| [`EmbeddedHost`](#embeddedhost) | struct | A running host with no listener, answering requests handed to it. |
| [`WindowRequest`](#windowrequest) | struct | Marks a request the window handed to the router. The window refuses pages from other origins itself, before routing, so the cookie CSRF check (`csrf::require_csrf_for_cookie_api`), which compares `Origin` with `integrations.public_origin`, does not apply. Only the embedded host can set it: it is a request extension, not a header. |
| [`TrackError`](#trackerror) | enum | Why a track cannot be played, in words for the listener. |
| [`MAX_RESPONSE_BYTES`](#max_response_bytes) | constant | Largest response body the window receives. Larger answers (none of the web app's routes produce one) become `502 Bad Gateway`. |
| [`RESPONSE_TIMEOUT`](#response_timeout) | constant | Longest a single request may take before it is answered with `504 Gateway Timeout`. A route that streams without end (none should be reachable here) would otherwise hold the request forever. |

## Re-exports

- [`bookclerk_window_policy::live_refusal`](/docs/internals/crates/bookclerk_window_policy/index.md#live_refusal)
- [`bookclerk_window_policy::LiveRefusal`](/docs/internals/crates/bookclerk_window_policy/index.md#liverefusal)
- [`bookclerk_window_policy::Navigation`](/docs/internals/crates/bookclerk_window_policy/index.md#navigation)
- [`bookclerk_window_policy::APP_ORIGINS`](/docs/internals/crates/bookclerk_window_policy/index.md#app_origins)
- [`bookclerk_window_policy::EMBEDDED_ORIGIN`](/docs/internals/crates/bookclerk_window_policy/index.md#embedded_origin)
- [`bookclerk_window_policy::MAIN_WINDOW_LABEL`](/docs/internals/crates/bookclerk_window_policy/index.md#main_window_label)
- [`bookclerk_media::PcmHeader`](/docs/internals/crates/bookclerk_media/pcm_wire/index.md#pcmheader)
- [`bookclerk_media::PcmStream`](/docs/internals/crates/bookclerk_media/index.md#pcmstream)

## Modules

- [`session`](/docs/internals/crates/bookclerkd/embedded/session/index.md): Who the desktop window is: the patron whose session this branch keeps sealed for its window, and the session cookies the window holds for them where the page cannot see them.

## Structs

### EmbeddedOptions

```rust
pub struct EmbeddedOptions {
    pub bookclerk_files: Option<PathBuf>,
    pub config: Option<PathBuf>,
}
```

Where the embedded host reads its files and configuration, as
`bookclerkd`'s `--bookclerk-files` and `--config` do.

**Fields**

- `bookclerk_files`: Bookclerk files directory; `None` uses `BOOKCLERK_FILES_DIR` or the
  platform default.
- `config`: Path to `config.toml`; `None` uses the one in the files directory.

Implements: `Clone`, `Debug`, `Default`

### EmbeddedHost

```rust
pub struct EmbeddedHost {
    /* private fields */
}
```

A running host with no listener, answering requests handed to it.

#### EmbeddedHost::start

```rust
pub async fn start(options: EmbeddedOptions, syslog_identifier: &str) -> Result<Self>
```

Loads the configuration, installs logging and starts the host.

Call it once per process, from inside a Tokio runtime that outlives
the host: the background runtimes run on it.

##### Arguments

* `options` - Where the files directory and configuration are.
* `syslog_identifier` - The name the OS log facility records for this
  process.

##### Returns

The running host.

##### Errors

Returns an error when the configuration cannot be loaded or the host
cannot start (an interrupted shared branch join, a control plane that does
not open, or operator auth that cannot be built).

#### EmbeddedHost::handle

```rust
pub async fn handle(&self, request: Request<Vec<u8>>) -> Response<Vec<u8>>
```

Answers one request from the window.

##### Arguments

* `request` - The webview's request. Only its method, path, query,
  body and non-credential headers are used.

##### Returns

The router's response, whole, without `Set-Cookie`; or `403` for a
request from another origin, `404` for a refused path, `502` for an
oversized body, `504` on timeout.

#### EmbeddedHost::navigation

```rust
pub fn navigation(&self, url: &str) -> Navigation
```

Decides whether the window may show `url`.

##### Arguments

* `url` - Where the window is about to go.

##### Returns

What the window should do (see [`Navigation`](/docs/internals/crates/bookclerk_window_policy/index.md#navigation)). A
`Navigation::SignInReturn` also closes the sign-in window.

#### EmbeddedHost::live

```rust
pub async fn live(&self, send: impl FnMut(String) -> bool + Send)
```

Feeds the live frames the SPA's `/api/live` socket would carry, for
the shell to forward to the page: `hello` with every topic, then a
`changed` frame for each change. The frames name topics only, so a
patron's window hears the same ones the operator's would.

Runs until `send` answers false. The frames name topics only, as on
the socket.

##### Arguments

* `send` - Takes each frame's JSON text; false stops the feed.

#### EmbeddedHost::open_track

```rust
pub async fn open_track(&self, path: &str, start_ms: u64) -> Result<PcmStream, TrackError>
```

Opens a play session's track for the window's own player, decoded
to PCM by a confined media worker from `start_ms`. The bytes are
read through the session's stream route,
so its checks apply to every block.

##### Arguments

* `path` - The track's stream path, as the session listed it.
* `start_ms` - Where to start, in milliseconds into the track.

##### Errors

A [`TrackError`](#trackerror) when the path is not a session's track, the route
refuses it, or the worker cannot decode it.

#### EmbeddedHost::shutdown

```rust
pub async fn shutdown(&self)
```

Stops the integration watchers before the process exits, as
`bookclerkd` does on shutdown.

Implements: `Debug`

### WindowRequest

```rust
pub struct WindowRequest;
```

Marks a request the window handed to the router. The window refuses
pages from other origins itself, before routing, so the cookie CSRF
check (`csrf::require_csrf_for_cookie_api`), which compares `Origin` with
`integrations.public_origin`, does not apply. Only the embedded host can
set it: it is a request extension, not a header.

Implements: `Clone`, `Copy`, `Debug`

## Enums

### TrackError

```rust
pub enum TrackError {
    NotATrack,
    SessionEnded,
    Refused(u16),
    UnknownSize,
    Media(String),
}
```

Why a track cannot be played, in words for the listener.

**Variants**

- `NotATrack`: The path is not a play session's track.
- `SessionEnded`: The session ended (closed, idle, or the edition changed): the
  player opens a new one.
- `Refused`: The stream route refused the track.
- `UnknownSize`: The track's size could not be read from the route's answer.
- `Media`: The media worker could not start or decode the track.

Implements: `Clone`, `Debug`, `Display`, `Eq`, `Error`, `PartialEq`

## Constants

### MAX_RESPONSE_BYTES

```rust
pub const MAX_RESPONSE_BYTES: usize = _;
```

Largest response body the window receives. Larger answers (none of the
web app's routes produce one) become `502 Bad Gateway`.

### RESPONSE_TIMEOUT

```rust
pub const RESPONSE_TIMEOUT: Duration = _;
```

Longest a single request may take before it is answered with
`504 Gateway Timeout`. A route that streams without end (none should be
reachable here) would otherwise hold the request forever.
