# HTTP API

# HTTP API

All API routes are under `/api/v1`, the documented base, and authenticate with
an `Authorization: Bearer` credential, except health and login. Two credential
kinds are accepted on the same header: a session JWT from
`POST /api/v1/auth/login`, and an opaque API token for machine clients
(`sfk_<prefix>_<secret>`), created and revoked at
`/{workspace}/account/api-tokens`.

The API reads only that header, never the session cookie. A request that carries the
session cookie without a `Bearer` credential is treated as a browser request and
must be same-origin, or it is refused with `403`; a `Bearer` request is
never affected.

**`/api` is a frozen alias.** It predates `/api/v1` and serves the
same handlers at the same paths it always has, so an existing integration (for
example Sarracenia's CI publishing through `sfk_` tokens) keeps working with no
change. New work targets `/api/v1`. The two bases differ only on the three
names `/api/v1` cleaned up, listed under Routes below; every other route
answers identically on both. `/api` is not deprecated and will not be removed;
it is simply never where a new route or a rename lands.

**An API route always answers with JSON**, whatever the request's `Accept` header
says. `error_html_middleware` turns a JSON error body into a styled page
for a browser, and it counted `*/*` as a preference for HTML, which is what curl
sends by default, what `fetch` sends with no `Accept` set, and what a good many
client libraries send. So a JSON request to a JSON route received an HTML document
and the client reported whatever its parser said instead of the reason. A request
that declares itself XHR is treated the same way, because the admin's own JSON
surfaces (autosave, the previews, the theme refresh) sit under a workspace prefix
rather than under `/api` and parse what they get.

An API token is scoped to one site, never outranks the account that issued it,
carries a scope that narrows what it reaches, and can be revoked or given an
expiry. The token page names that site: the create panel and the
new-token panel both state the site's name and slug, and the tokens table
carries a Site column, so an operator confirms the target before and after
creating a token. The site is the one the token was created for: the account's
home site on the shared host, and on a configured docs or blog host that host's
site, whatever the creator's organization or home site (only a super admin
reaches the token page there). A token minted on
such a host is always `content` scope, and on that host the page lists only the
tokens bound to its site. A token is usable by an owner who may use its site (a
super admin anywhere, any other role on its own site or a site of its own
organization), and a request on a docs or blog host with a token bound to
another site answers 403 naming both sites. The browsers the new-device approval gate
recognizes are managed the same way, at `/{workspace}/account/devices`: the
owner sees when each was first seen and last used, which one they are reading
on, and removes any of them after confirming their password. A removed device is
not signed out; it stops being recognized, so its next sign-in is held for
approval.

## Routes

```
GET      /api/v1/health
POST     /api/v1/auth/setup                 # First-time setup; site_slug must be [a-z0-9-]
POST     /api/v1/auth/login                 # Returns JWT, or 202 when held for approval
GET      /api/v1/auth/login/approval/{ref}  # Poll a held sign-in; returns the JWT once approved
POST     /api/v1/auth/magic-link            # Request a sign-in link by email
POST     /api/v1/auth/refresh               # Refresh token
GET      /api/v1/auth/me                    # Current user; includes site_slug, the site the credential acts on
CRUD     /api/v1/content-types              # Content type schemas; PUT takes renames/removed_fields, and shape for a generic -> catalog transition
GET      /api/v1/content-templates          # Built-in template catalog, including the catalog-shape "product" template
POST     /api/v1/content-types/from-template # Copy-on-apply a template; 404 unknown, 409 taken slug, admin-only
CRUD     /api/v1/content                    # Content entries; GET takes ?type= and ?slug=, POST takes status. Writes validate data against the schema. Every entry also carries summary, cover_media_id, meta_title and meta_description, the document shape's typed columns. On a catalog-shape type, GET also takes ?sort=price|-price, ?min_price=, ?max_price= and ?in_stock=. On a profile-shape type, GET also takes ?country= and ?region=
POST     /api/v1/content/push               # Idempotent bulk write of one content type; validates each row before writing any of it
PATCH    /api/v1/content/{id}/status        # Change one entry's status
CRUD     /api/v1/authors                    # Blog bylines
CRUD     /api/v1/terms?taxonomy=             # Terms in any taxonomy slug matching [a-z0-9-]{1,40}; category and tag are the blog's own (opened to any name)
GET/PUT/DELETE   /api/v1/products/{content_id}/pricing              # Product base price
GET/POST         /api/v1/products/{content_id}/variations           # Product variations
PUT/DELETE       /api/v1/products/{content_id}/variations/{variation_id} # One variation
CRUD             /api/v1/customers                                 # Storefront shoppers, distinct from staff users
GET/POST         /api/v1/orders                                    # Orders; POST resolves price and stock server-side
GET              /api/v1/orders/{id}                                # One order with its items
PATCH            /api/v1/orders/{id}/status                         # Change an order's status
POST             /api/v1/orders/{id}/checkout                       # Start checkout for an order against a payment method
GET/POST         /api/v1/payment-methods                             # Payment methods; secrets are write-only, never returned
GET/PUT/DELETE   /api/v1/payment-methods/{id}                         # One payment method
POST             /webhooks/payments/{method_id}                   # Stripe webhook; mounted outside /api/v1, no session or API token
GET/PUT/DELETE   /api/v1/events/{content_id}/schedule               # Event schedule: start, end, timezone, place
GET              /api/v1/events?from=&to=&limit=                    # Upcoming published events, ordered by starts_at
GET/PUT          /api/v1/galleries/{content_id}/items               # Ordered, captioned media items of a gallery
GET/PUT/DELETE   /api/v1/profiles/{content_id}                      # Profile contact and address columns; PUT/DELETE admin-only
CRUD     /api/v1/pages                      # Pages (reads report published / published_revision / published_at)
GET      /api/v1/pages?source=&external_id= # Find a pushed page by the pipeline's own identifier
GET      /api/v1/pages?path=                # Find a page by the path it serves
GET      /api/v1/pages?version=             # Filter by the optional free-form version label, exact match
POST     /api/v1/pages/push                 # Idempotent bulk write of a page tree
GET/PUT  /api/v1/pages/{id}/widgets         # Page widgets
POST     /api/v1/pages/{id}/publish         # Make the page's current draft live
POST     /api/v1/pages/{id}/unpublish       # Take the page off the site, keeping its draft
GET      /api/v1/widgets/types              # The widget-type catalog the admin picker is built from
GET/PUT  /api/v1/layout                     # Global widgets, renamed from widgets/global
CRUD     /api/v1/menus                      # Menus
PUT      /api/v1/menus/{id}/items           # Menu items
CRUD     /api/v1/users                      # Users
GET/PUT  /api/v1/sites/current/settings     # Site settings, renamed from site/settings
GET      /api/v1/sites                      # Every site on the instance (super admin)
POST     /api/v1/sites                      # Create a site and its organization (super admin)
POST     /api/v1/export                     # Trigger a static export of the caller's site; admin only
POST     /api/v1/import/woocommerce         # Import a WooCommerce product CSV export; admin only
POST     /api/v1/media                      # Upload a file into the caller's own site's media library; admin/super_admin role, and a content-scoped token
```

Every route above also answers at the same path under `/api` (the frozen
alias), except the three renamed in `/api/v1`: there it keeps serving under its old
name instead, `GET/PUT /api/site/settings`, `PUT /api/orders/{id}/status` and
`GET/PUT /api/widgets/global`. Everywhere else in this document, an unqualified
`/api/...` route mentioned in prose or an example answers identically under
`/api/v1`.

`GET /api/v1/dev/invite-setup` also exists, but only as a dev and test helper:
it returns the current setup link for a requested email so the Playwright
onboarding suite can complete an invite.

## Creating and addressing a site

Two things a docs pipeline needed and did not have.

### Creating one

`POST /api/sites` takes `name`, `slug`, and optionally `domain`, `theme` and `is_default`. It is **super admin only**, not `require_admin` and not the content scope: creating a site creates a tenant and an organization with it, which is platform-level, so a site-scoped credential must not reach it however privileged it is inside its own site.

It shares `admin::sites::provision_site` with the admin form rather than reimplementing it, because the organization a site belongs to is derived from its theme and two copies of that rule would drift.

One thing to know before automating it: a super admin with no confirmed second factor is refused every credential path (`User::require_two_factor_enrollment`), so the sequence is that a person enrols once, mints a machine token, and the pipeline uses that. The enrolment is not automatable and is not meant to be.

### Addressing one

A site is reached by host. `{slug}.{shared_host}` selects one for any host listed in `STOREFRONT_SHARED_HOSTS`, so `psa-docs.localhost` reaches the site `psa-docs` with no DNS and no domain configured on it, because a browser resolves `*.localhost` to loopback (RFC 6761).

That rule used to require the shared host to start with `storefront.`, which none of the defaults do, so it was dormant exactly where it was useful. The consequence was that a multi-site instance could not address a site at all without a domain: the default-site fallback stops once a second site exists, deliberately, so an unmatched host resolves to nothing.

The invariant is unchanged and is the point: **a host the operator never declared shared still resolves to no site.** Declaring a host shared already means "this host serves many tenants", so a label in front of it selecting one is what the declaration was for.

## Pushing content from an external pipeline

The routes above are addressed by id and shaped for a person working
through the admin. A generated documentation set has a different problem: it
knows its own identifiers and not Storefront's, it re-pushes the same tree on
every build and must not accumulate duplicates, it needs a tree of hundreds of
pages in one call, and a half-applied tree is worse than none. `POST
/api/pages/push` and `POST /api/content/push` answer that, on top of the same
model writes the rest of the API uses rather than beside them.

### The key

A pushed row is keyed on `(site_id, external_source, external_id)`. `source`
names the pipeline; `external_id` is whatever the pipeline calls the row. Both
are stored on the row (`pages.external_source`, `pages.external_id`, and the same
pair on `content`), which is also what the admin reads to warn that a page is
externally managed.

`pages` already carries `UNIQUE (site_id, path)` and `content` carries
`UNIQUE (site_id, content_type_id, slug)`, so a push could have keyed on those.
It does not, because renaming a page changes its path, and a push keyed on path
reads a rename as a delete plus a create: the page loses its publication revision
history and every inbound link breaks. The pipeline's own identifier survives a
rename, so the row does too.

### Pushing a page tree

```
POST /api/pages/push
{
  "source": "docs-pipeline",
  "prune": true,
  "pages": [
    { "external_id": "index", "title": "Docs", "slug": "docs", "path": "/docs",
      "widgets": [{ "widget_type": "markdown", "region": "main", "config": { "source": "# Docs" } }] },
    { "external_id": "guide", "title": "Guide", "slug": "guide", "path": "/docs/guide",
      "parent_external_id": "index", "widgets": [...] }
  ]
}
```

- `parent_external_id` names another page **of the same payload**. A parent
  outside the payload is refused by name rather than silently filed at the top
  level: in a full-tree push it would be a page about to be pruned, and in a
  partial push it is the pipeline guessing.
- `published` defaults to `true`. A generated page that is not published is not
  serving anybody. Sending `false` retracts the publication and keeps the draft
  row, so the next push can put it back. The push also writes `pages.status` in
  its structural transaction: `published` for a published page,
  `draft` for a retracted one (an `archived` page stays archived), so status
  readers and link bases agree with the publication.
- `visibility`, `template`, `meta_title`, `meta_description`, `sort_order` and
  `version` are the same fields `POST /api/pages` takes, validated the same
  way. `version` is omitted-key-writes-unset, the same as `meta_title`: a push
  that used to send a version and stops sending it clears the row's, it does
  not leave the old one in place.
- `prune` defaults to `true`: pages this source owns that the payload no longer
  names are deleted. That is what makes the pipeline the source of truth rather
  than an append-only writer. A pipeline pushing one page at a time must send
  `false`.

The answer counts what happened, so a pipeline can assert on it:

```json
{ "source": "docs-pipeline", "created": 0, "updated": 4, "unchanged": 4,
  "pruned": 0, "published": 0, "retracted": 0 }
```

`unchanged` is the number of pages whose publication did not move, which is what
a re-push of an unmodified tree should report for every page.

#### Push history and pausing (SF-500)

Every `POST /api/pages/push` and `POST /api/content/push` that passes
authentication and scope is recorded as one row of `content_push_runs` (token,
source, counts, the pages or entries touched, status `succeeded` or `failed`, the
error text capped at 500 characters) and listed on the docs site's Docs sync
screen. A request refused for authentication or scope never reaches the handler
and is not recorded. Each site keeps its newest 500 rows.

Both bodies accept an optional `provenance` object, kept in that history only:
`repo_url` and `run_url` (https), `commit` (7 to 64 hex characters), `ref_name`
(200 characters), `message` (first line, 300 characters), `author_name` (100) and
`author_email`. A field that breaks its rule answers `400` naming it
(`provenance.commit must be 7 to 64 hex characters.`) and the push is recorded as
failed.

While a super admin has paused syncing for the site, a push is authenticated and
parsed as usual, stored with its payload, and answered `202`:

```json
{ "held": true, "run_id": "9b0c6a4e-0c55-4f52-8d52-0f6f6f6f6f6f" }
```

Nothing is written to pages. A newer held push of the same source and endpoint
replaces the older one (`superseded`, payload dropped), since a push is a full
snapshot. Resuming applies the newest held push of each source once and records
its outcome on the same row.

### Pushing content entries

```
POST /api/content/push
{ "source": "docs-pipeline", "type": "docs-page", "prune": true,
  "items": [{ "external_id": "a", "title": "Alpha", "slug": "alpha", "data": {...}, "status": "published" }] }
```

`type` is the content type's slug, not its id, because a pipeline knows
`docs-page` and not a UUID minted on a site it has never read. `status` defaults
to `published`, for the same reason a pushed page is live.

`POST /api/content` still takes a `content_type_id`, not a slug: the push route
above is the one a pipeline uses, and the authors and taxonomy features made that
field required on the create wrapper. It does accept a `status`, so a create no
longer needs a follow-up `PATCH .../status`.

### What "applied atomically" means here

The whole payload is validated before anything is written: every path, slug,
template and widget type, the parent references, a path two pages both claim, and
a path that belongs to a page this source does not own. A payload with one bad
page writes none of it.

The structural write then runs as one transaction through
`db::execute_transaction` (`src/db.rs:199`), so the rows, their
parents and their widgets land together or not at all.

Going live is deliberately not in that transaction.
`PagePublication::upsert_from_draft` is the single writer of a publication
revision and opens its own transaction, so publications run after
the structural write commits. That is safe because publishing is idempotent:
`matches_draft` short-circuits an unchanged page, so a re-push does not advance a
revision number, and a push interrupted between the two steps converges on the
next one. For that short-circuit to work the push has to keep a widget row's id
when it puts a widget back in the same place, because the publication snapshot
records widget ids; `widget_ids_for`
(`src/content_push.rs`) is what does that.

A push carries at most `MAX_PUSH_ROWS` rows (2000). The whole payload is held in
memory and planned as statements before anything runs, so that is a memory bound
rather than a policy.

### Token scope

A machine token carries a scope as well as a role:

- `full` is what every token minted before token scopes existed was: the issuing account's own
  role, unrestricted.
- `content` reaches pages, content entries and content types, and nothing else. A
  docs pipeline needs nothing more, so the credential it holds cannot create a
  user, change the site's settings or replace the global widgets.

The scope only ever narrows. A `content` token still cannot do anything its
owner's role could not, because `require_content_write`
(`src/auth/middleware.rs`) checks the same roles
`require_admin` does; `require_admin` additionally refuses any narrowed token, so
every route already guarded by it is closed to a content pipeline without any of
those routes being edited.

The scope is chosen when the token is minted, at
`/{workspace}/account/api-tokens`, and shown in the token list. On a configured
docs or blog host the host chooses: the token is bound to that host's site with
scope `content`, and the form field is ignored. The docs host's Docs sync screen
also creates, regenerates and revokes these tokens (super admin only).

When no scope is named, a token defaults to `full`, or to `content` on an instance started with `STOREFRONT_INSTANCE_ROLE=content`; the form preselects the same default.

### Externally managed content in the admin

A page or entry whose `external_source` is set says so in the admin: a badge in
the list and a warning on the form, both saying that edits made there last until
the next push and that the change belongs at the source. The API is the source of
truth for those rows and the UI is secondary, so the UI says so rather than
letting an editor find out when their work disappears.

### An optional version label on pages

`pages.version` and `page_publications.version` are a free-form,
optional `TEXT` column, no default and no backfill
(`migrations/{postgres,sqlite}/20261004000001_page_version.sql`). There is no
semver or other format check: a trimmed, non-blank value up to 64 characters is
accepted as-is, so a pipeline can use its own release tags, dates, or commit
hashes. `normalized_version()` (`src/page_input.rs`) is
the single function every surface runs it through: blank or omitted clears the
field, over 64 characters or containing a control character is a 422. `POST
/api/pages` and `PUT /api/pages/{id}` take it; `PUT` follows the same
absent-vs-null-vs-value rule as `parent_id` (absent leaves it unchanged, `null`
clears it, a value sets it). `GET /api/pages` and `GET /api/pages/{id}` return
it, and `GET /api/pages?version=` filters on it, exact and case-sensitive.
Publishing copies the draft's `version` onto the live snapshot the same way it
copies `visibility`, so a draft edit does not change what a reader sees until
the page is republished; `page_publication_revisions` predates the column and
never carries it, so restoring a historical revision leaves the draft's
current version alone. It is deliberately left out of `<page>.md` and
`/llms.txt`.

### Triggering a static export

`POST /api/export` (`src/api/export.rs:28`) is the
step that finishes the pipeline: push pages and content with the routes above,
then call this route to rebuild the site's static export from what is now live.
It requires an admin credential (`auth.require_admin()`,
`src/api/export.rs`), so a narrowed `content`-scope
token cannot trigger it.

The export is a full rebuild every time, written to
`data/sites/{site_id}/export` (`src/export.rs:30`), and
responds with an `ExportSummary`:

```json
{ "output_dir": "data/sites/<site_id>/export", "pages_exported": 12,
  "pages_skipped": 1, "assets_copied": 34, "warnings": [
    { "page_path": "/members", "widget_type": null, "detail": "..." }
  ] }
```

`pages_skipped` and `warnings` cover what cannot survive a static rebuild: a
page whose `visibility` is `authenticated` has no static equivalent and is
skipped rather than exported half-gated, and a widget that calls back into the
running application (`contact_form`, `search`, or `newsletter` with no external
`action_url`) is reported as a warning rather than left to fail silently once
the export is served with no Storefront instance behind it.

## Content data validation and schema migration

A content type's `schema` is not just a form-builder hint: every write
of `content.data` is checked against it by one function,
`validate_content_data()` (`src/content_validation.rs:105`),
so `POST /api/content`, `PUT /api/content/{id}`, the admin content-item form
and its autosave, and `POST /api/content/push` all refuse the same bad row the
same way rather than four places drifting. A required field that is missing,
blank, or (for a checkbox) not `true`; a `number` field whose value does not
parse as a number; an `email` or `url` field that is not a well-formed one; and
a `select` field whose value is not one of its own `options`, are each reported
as one `FieldError` (`src/content_validation.rs:16`),
`{ "field", "message" }`. A key in `data` that the schema does not declare is
left alone rather than rejected, since a schema can grow without a coordinated
rewrite of every existing row.

On the JSON API, `POST /api/content` and `PUT /api/content/{id}`
(`create_content()`, `src/api/content.rs:238`;
`update_content()`, `src/api/content.rs:299`) answer
`422 Unprocessable Entity` with `{ "errors": [ { "field", "message" }, ... ] }`
through the shared `validation_error_response()`
(`src/api/content.rs`), and log a `warn` naming the
failing fields. Nothing is written when validation fails.

`POST /api/content/push` (`push_content()`, `src/api/content.rs:411`)
validates every row before any statement for that row is queued, so **the
first invalid row in a batch fails the whole push and writes none of it**,
answering `422` with `{ "external_id", "errors" }` naming the offending row by
the pipeline's own identifier rather than a row number or a database id.

## Renaming or dropping a content type field

Changing a field's `key` or deleting a field from a content type's
schema used to leave every existing row's `content.data` keyed on the old
shape, silently. `PUT /api/content-types/{id}` (`update_content_type()`,
`src/api/content_types.rs`) now takes two
additional, optional request fields alongside `schema`:

```json
PUT /api/content-types/{id}
{
  "schema": { "fields": [ { "key": "about", "label": "About", "type": "textarea" } ] },
  "renames": { "bio": "about" },
  "removed_fields": { "legacy_note": "drop" }
}
```

- `renames` maps an old field key to its new one. Every existing row of that
  content type has its `data` rewritten from the old key to the new one.
- `removed_fields` maps a field key that no longer appears in `schema` to
  either `"drop"` (the key is deleted from every row's `data`) or `"keep"`
  (the value is left in `data`, unreferenced by the schema but not lost).

Both are carried in one transaction alongside the content type's own row
update, by `ContentType::update_for_site_with_migration()`
(`src/models/content_type.rs`), through the
same backend-agnostic `Statement`/`execute_transaction` primitives the rest of
`src/db.rs` uses, so a Postgres or SQLite site either migrates every row and
the schema together or changes nothing.

A `renames` entry whose target key already belongs to another field that is
not itself being renamed away is refused with `409 Conflict`
(`SchemaMigrationError::RenameCollision`,
`src/models/content_type.rs`), naming the
colliding key, rather than silently merging two fields' data together.

The response body adds `rows_missing_required`
(`ContentTypeUpdateOutcome`, `src/models/content_type.rs:52`):
the count of existing rows that lack a field the updated schema now marks
required. Making a field required does not retroactively validate or touch
those rows, since a schema edit is not itself a content edit; it only reports
how many rows an editor now needs to revisit.

The admin schema editor (`templates/admin/content_type_form.html`) sends the
same two fields: removing a field that already had a key when the page loaded
prompts the editor to keep or drop its stored data before the form can save,
and renaming a field's key (rather than adding a new one) is detected by
comparing against that same original key.

## Blog: authors and taxonomy

The blog feature is built on the generic `Content` model, but a byline and a category/tag are not content fields: an author is not always a login-holding user (a byline may credit someone who never signs in), and a category or tag is shared across every article that carries it rather than typed fresh on each one. Two small CRUD modules manage those, `src/api/authors.rs` and `src/api/terms.rs`, both mounted under `/api` alongside the rest of the content API (`src/api/mod.rs:124-125`).

### `/api/authors`

`routes()` (`src/api/authors.rs:67`) registers `GET/POST /api/authors` and `GET/PUT/DELETE /api/authors/{id}`, all site-scoped to the caller's `auth.site_id`. `GET` is open to any authenticated caller (`list_authors()`, `src/api/authors.rs:12`; `get_author()`, `src/api/authors.rs:30`); `POST`, `PUT` and `DELETE` call `auth.require_admin()` first (`create_author()`, `src/api/authors.rs:20`; `update_author()`, `src/api/authors.rs:41`; `delete_author()`, `src/api/authors.rs:54`).

An author is `name`, `slug`, `bio`, and an optional `user_id`: `user_id` is optional because an author may write under a byline without ever holding a login, so it only links back to the platform account when one exists. `slug` is what `/blog/author/{slug}` resolves. An author is no longer its own table but profile-shaped content (the same `shape: "profile"` that "Profiles: typed contact and address columns" below describes) on the built-in `author` content type, so `Author` (`src/models/author.rs:25`) is a thin layer over `Content` and `Profile` that keeps this same JSON shape and these same routes; `ensure_author_type()` (`src/models/author.rs:90`) provisions that content type lazily, mirroring how `ensure_article_type()` provisions `article`.

### `/api/terms`

`routes()` (`src/api/terms.rs:92`) registers `GET/POST /api/terms` and `GET/PUT/DELETE /api/terms/{id}`. A term (`src/models/term.rs`) is `taxonomy`, `name` and `slug`, unique on `(site_id, taxonomy, slug)`, so two terms in different taxonomies may share a slug without colliding. `category` and `tag` (the constants `CATEGORY`/`TAG`) are the blog's own taxonomies, but the field is open: any taxonomy exists once it has terms, with no separate declaration, so `taxonomy` needs only to match `[a-z0-9-]{1,40}` (`valid_taxonomy()`, `src/api/terms.rs:18`), checked on every read and write, `400` on anything else. `GET /api/terms?taxonomy=` (`list_terms()`, `src/api/terms.rs:33`) defaults to `category` when the query param is absent, and answers an empty list for a taxonomy with no terms yet. `create_term()` (`src/api/terms.rs:44`), `get_term()` (`src/api/terms.rs:55`), `update_term()` (`src/api/terms.rs:66`) and `delete_term()` (`src/api/terms.rs:79`) round out the CRUD; `update_term()` only ever changes `name`, since `taxonomy` and `slug` are what a route and a unique index key on, not something a caller edits in place.

Both modules follow the same shape every other CRUD module in `src/api/` uses: `auth.require_admin()` on the write verbs, a scoped `list_by_site`/`get_by_id_for_site` pair for reads, and a `{"deleted": true}` body on a successful delete. Neither is wired into `content/push` or `pages/push`: an external pipeline pushing article content still creates authors and terms through these routes (or leaves an article with none), not through the bulk-push payload.

## Commerce: products, variations and customers

A product is a `content` item like any other, so `POST /api/content` already creates and titles it; these routes add the two things a generic content entry does not carry: a price, and the shopper who might buy it. Two modules cover that, `src/api/products.rs` and `src/api/customers.rs`, both mounted under `/api` alongside the rest of the content API (`src/api/mod.rs:125-126`).

A content type's `shape` gates every pricing and variation write: `require_catalog_content()` (`src/api/products.rs:45`) loads the content and its type and answers `422` (`{"errors": [{"field": "content_type", ...}]}`) unless `shape == "catalog"`, since only a catalog-shape type carries the typed price/SKU/stock columns these routes write. The built-in `product` template (`src/content_templates.rs`, `CATALOG`) applies through `POST /api/content-types/from-template` with `shape: "catalog"` already set; an existing `generic` type can also become `catalog` through `PUT /api/content-types/{id}` by naming `shape: "catalog"` in the body, the only transition `update_for_site_with_migration()` (`src/models/content_type.rs`) accepts, `409` on any other requested shape change.

### `/api/products/{content_id}/pricing`

`routes()` (`src/api/products.rs:178`) registers `GET/PUT/DELETE /api/products/{content_id}/pricing`, site-scoped to the caller's `auth.site_id` and to a `content_id` that must already exist for that site (`require_content_for_site()`, `src/api/products.rs:22`). `GET` is open to any authenticated caller (`get_product_pricing()`, `src/api/products.rs:64`); `PUT` and `DELETE` call `auth.require_admin()` first (`set_product_pricing()`, `src/api/products.rs:76`; `delete_product_pricing()`, `src/api/products.rs:99`). A caller sets `base_price_cents` (required) and `currency` (optional, defaults to `USD`) on `PUT`; both live on the `products` row (`src/models/product.rs`) rather than inside `content.data`, so they stay queryable. `PUT` upserts: the first call creates the pricing row, a later one updates it in place. Catalog-shape types add three more columns to that same row and to the same `PUT`: `sku` (optional, unique per site when set, checked with a pre-check query against `Product::content_id_for_sku()` before the write rather than by catching the partial unique index's own violation, `409` on a collision with a different product), `compare_at_price_cents` (optional) and `stock_quantity` (optional; `null`/absent means untracked and always available, a number is a real count a sale can deplete).

### `/api/products/{content_id}/variations`

`routes()` (`src/api/products.rs:178`) also registers `GET/POST /api/products/{content_id}/variations` and `PUT/DELETE /api/products/{content_id}/variations/{variation_id}`. `GET` (`list_variations()`, `src/api/products.rs:112`) is open to any authenticated caller; `POST`, `PUT` and `DELETE` require admin (`create_variation()`, `src/api/products.rs:123`; `update_variation()`, `src/api/products.rs:141`; `delete_variation()`, `src/api/products.rs:164`). A variation (`src/models/product_variation.rs`) is a priceable, stockable option on a product: a caller sets `sku` (required on create), `axis_values` (a JSON object of axis name to value, since the axis set, such as size or colour, is defined per product rather than by a fixed schema), `price_override_cents` (optional; a variation has no currency of its own, only a possible override of the product's), and `stock_quantity`. An update also takes `clear_price_override` to drop an override back to the product's base price, since `PUT` otherwise leaves an unset field unchanged rather than nulling it. A catalog-shape content type declare its axis set up front, in `schema.variation_axes` (an array of up to three axis names); `validate_variation_axes()` (`src/models/product_variation.rs`) then requires `axis_values` on create to carry exactly those keys, no more and no fewer, `422` on an undeclared key or a missing one, and applies the same check to `axis_values` on update when the caller sends it.

### Catalog filtering and sorting

`GET /api/content?type=<slug>` answers `min_price`, `max_price` (cents, inclusive, matching `base_price_cents`), `sort` (`price` or `-price`) and `in_stock` (`true` keeps only a row with a `products` entry whose `stock_quantity` is untracked or greater than zero) when `type` names a catalog-shape content type (`list_content()`, `src/api/content.rs:167`; `Content::list_by_type_with_catalog_filters()`, `src/models/content.rs`). A non-catalog type ignores all four and keeps the newest-first list every other content type already returns.

### `/api/customers`

`routes()` (`src/api/customers.rs:69`) registers `GET/POST /api/customers` and `GET/PUT/DELETE /api/customers/{id}`, all site-scoped and all requiring admin (`list_customers()`, `src/api/customers.rs:12`; `create_customer()`, `src/api/customers.rs:21`; `get_customer()`, `src/api/customers.rs:31`; `update_customer()`, `src/api/customers.rs:43`; `delete_customer()`, `src/api/customers.rs:56`). A customer (`src/models/customer.rs`) is a storefront shopper, deliberately separate from `users`: a user is a staff account with a password and a role that signs in to manage a site, while a customer buys from it and needs no login here. A caller sets `email` (required), `name` (defaults to empty), `phone` and `notes`, both optional.

## Orders

An order is a checkout record, not a `content` row: `src/models/order.rs` and `src/api/orders.rs` (mounted at `src/api/mod.rs:139`) add `orders` and `order_items` tables rather than extending the content model, since an order's line items need typed price and stock resolution instead of a schema-driven JSON blob. `routes()` (`src/api/orders.rs:154`) registers `GET/POST /api/orders`, `GET /api/orders/{id}`, `PUT /api/orders/{id}/status`, and `POST /api/orders/{id}/checkout`, all site-scoped to `auth.site_id`. `GET` is open to any authenticated caller (`list_orders()`, `src/api/orders.rs:45`; `get_order()`, `src/api/orders.rs:53`); `POST`, the status `PUT`, and checkout require admin (`create_order()`, `src/api/orders.rs:30`; `update_order_status()`, `src/api/orders.rs:64`; `checkout_order()`, `src/api/orders.rs:111`).

### Payment methods and checkout

A site owns its own payment methods (`src/models/payment_method.rs`, migrations `20261001000002_payment_methods.sql`): a `stripe` method holds a secret key and webhook signing secret, and a `manual` method (cash, bank transfer, and so on) holds instructions to show the shopper. Either secret is sealed at rest with the same AEAD primitive TOTP seeds use (`src/sealing.rs`), but under a distinct HKDF context so a TOTP seed's ciphertext and a payment method's never open under each other even when both fall back to the same `JWT_SECRET`. `PaymentMethodView` (`src/models/payment_method.rs`) is the only shape ever returned or rendered; the `PaymentMethod` row itself is deliberately not `Serialize`, so a handler cannot return a secret by forgetting to map it away.

`routes()` (`src/api/payment_methods.rs:215`) registers `GET/POST /api/payment-methods` and `GET/PUT/DELETE /api/payment-methods/{id}`, all site-scoped and all requiring admin (`list_payment_methods()`, `src/api/payment_methods.rs:29`; `create_payment_method()`, `src/api/payment_methods.rs:43`; `get_payment_method()`, `src/api/payment_methods.rs:59`; `update_payment_method()`, `src/api/payment_methods.rs:71`; `delete_payment_method()`, `src/api/payment_methods.rs:87`). `POST` takes `provider` (`stripe` or `manual`), `label`, an optional `enabled`, and the provider's own fields (`secret_key` and `webhook_secret` for Stripe, `instructions` for manual); a provider missing a field it needs, or an unknown provider, is `422`. `PUT` lets any of those change without resending a secret that is not changing.

`POST /api/orders/{id}/checkout` (`checkout_order()`, `src/api/orders.rs:111`) takes `payment_method_id` and starts checkout for that order through `PaymentMethod::checkout()` (`src/models/payment_method.rs`): a Stripe method creates a hosted checkout session (`src/payments/stripe.rs`, a plain `reqwest` call with no SDK) and answers `{"outcome": "redirect", "url": ...}`; a manual method answers `{"outcome": "instructions", "text": ...}` immediately and leaves the order `pending` until an admin marks it paid through the existing `PUT /api/orders/{id}/status`. A disabled method is `409`, and a method id from another site is `404` the same way every other site-scoped lookup is.

`POST /webhooks/payments/{method_id}` (`stripe_webhook()`, `src/api/payment_methods.rs:128`, mounted at `src/main.rs` rather than under `/api`) is Stripe's own call and carries no session or API token, so every acceptance decision rests on its `Stripe-Signature` header verifying against that method's own webhook secret (`verify_signature()`, `src/payments/stripe.rs`, a hand-rolled HMAC-SHA256 since the signature scheme needs nothing else); a bad signature is `400`, leaves the order unchanged, and is recorded as the method's `last_error`. A validly-signed payload whose header `t=` timestamp is more than 5 minutes old or in the future (`SIGNATURE_TOLERANCE_SECS`, `verify_signature_at()`, `src/payments/stripe.rs`) is rejected the same way, as `400` recorded as `last_error`, so a captured signature cannot be replayed indefinitely. A `checkout.session.completed` event moves its order from `pending` to `paid` through `Order::update_status()`, whose own transition guard already refuses `paid -> paid`, so a duplicate delivery of the same event is a no-op `200` rather than needing a separate processed-event table.

`POST /api/orders` takes `customer_id` (optional) and `items` (`content_id`, an optional `variation_id`, and `quantity`). `Order::create()` (`src/models/order.rs:187`) does all the resolution server-side, in one transaction per attempt: it loads each item's `content`, requires its type's `shape` to be `catalog`, requires a `products` row to already carry pricing, and resolves the unit price through `Product::resolve_price()` (`src/models/product.rs`), a variation's `price_override_cents` if one is named, else the product's `base_price_cents`. Every item in an order must share one currency, `422` on a mismatch. Stock is checked and decremented in the same transaction: a named variation always draws from its own tracked `stock_quantity`, otherwise the product's, and `stock_quantity: null` on the product means untracked and never blocks or decrements. Insufficient stock leaves the whole attempt's transaction rolled back and answers `409`, so nothing is partially decremented. `number` is sequential per site (`UNIQUE(site_id, number)`), computed inside the same transaction as the insert; a losing insert (two sites' concurrent creates racing the same `MAX(number)` read) is detected by the unique-constraint violation and the whole attempt, not just the number, is retried in a fresh transaction, up to a handful of times.

`PUT /api/orders/{id}/status` takes `status` and only allows `pending -> paid`, `pending -> cancelled`, `paid -> fulfilled` and `paid -> refunded` (`Order::allowed_transition()`, `src/models/order.rs:718`); anything else is `422`. Only `pending -> cancelled` restores the stock the order decremented (`Order::update_status()`, `src/models/order.rs:725`); `paid -> refunded` does not, since a refund in this issue's scope is a payment-side reversal, not a return.

The admin dashboard's Orders pages (`src/admin/orders.rs`, `templates/admin/orders_list.html`, `templates/admin/order_detail.html`) render what `Order::list_by_site()` (`src/models/order.rs:696`) and `Order::get_by_id()` (`src/models/order.rs:671`) already return; the detail page also carries a status-transition form and a checkout-initiation form, both calling the same `Order::update_status()` and `PaymentMethod::checkout()` the API routes call. There is still no admin-side order-creation form, since that goes through `POST /api/orders` directly.

## Events: typed schedule and upcoming query

An event, class or workshop is a `content` item like any other, so `POST /api/content` already creates and titles it against a template with `shape: "event"` (the built-in `event` and `class` templates, `src/content_templates.rs`, `CATALOG`); no recurrence is supported, so a series is one row per occurrence rather than one row with a repeat rule. `src/models/event.rs` and `src/api/events.rs` (mounted at `src/api/mod.rs:131`) add a `content_events` table extending `content` one-to-one, the same pattern the `products` table set, since a generic `content.data` blob is not range-queryable and this schedule needs to answer "what's coming up between these two dates."

### `/api/events/{content_id}/schedule`

`routes()` (`src/api/events.rs:143`) registers `GET/PUT/DELETE /api/events/{content_id}/schedule`, site-scoped to `auth.site_id` and to a `content_id` that must already exist for that site (`require_content_for_site()`, `src/api/events.rs:34`; `404` across sites, matching `/api/products/{content_id}/pricing`). `GET` is open to any authenticated caller (`get_event_schedule()`, `src/api/events.rs:64`); `PUT` and `DELETE` require admin (`set_event_schedule()`, `src/api/events.rs:76`; `delete_event_schedule()`, `src/api/events.rs:98`). `PUT` also requires the content's type to carry `shape: "event"` (`require_event_content()`, `src/api/events.rs:46`), `422` on a `generic` or `catalog` type, since only an event-shape type has this table's row.

A caller sets `starts_at` and `timezone` (both required), and optionally `ends_at`, `all_day`, `location_name`, `address`, `capacity` and `registration_url`. `starts_at`/`ends_at` are absolute instants (RFC 3339); `timezone` is a plain IANA name (for example `America/New_York`) carried alongside them for display, not used to convert anything. `ends_at` before `starts_at` is `422`. `PUT` upserts: the first call creates the schedule row, a later one replaces it in place (`EventSchedule::upsert()`, `src/models/event.rs`).

### `/api/events`

`list_upcoming_events()` (`src/api/events.rs:118`) answers `GET /api/events?from=&to=&limit=`, open to any authenticated caller, across every event-shape content type on the site rather than one type at a time. `from` and `to` (both optional RFC 3339 instants) narrow the result to events starting in that inclusive range; `to` before `from` is `422`. `limit` defaults to 50 and is clamped to 200. Results are ordered by `starts_at` ascending and, like every other "published" list in this API, only include a `content` row whose `status` is `published` and whose `publish_at` is null or already past (`EventSchedule::list_upcoming_published()`, `src/models/event.rs`), so a draft event or one scheduled to go live later never appears here even if its `starts_at` falls inside the requested range.

## Profiles: typed contact and address columns

A team member, store location or testimonial is a `content` item like any other, so `POST /api/content` already creates and titles it against a template with `shape: "profile"` (the built-in `team-member`, `location` and `testimonial` templates, `src/content_templates.rs`, `CATALOG`). `src/models/profile.rs` and `src/api/profiles.rs` (mounted at `src/api/mod.rs:132`) add a `content_profiles` table extending `content` one-to-one, the same pattern the `products` and `content_events` tables set, since a generic `content.data` blob cannot be queried by country or region.

### `/api/profiles/{content_id}`

`routes()` (`src/api/profiles.rs:97`) registers `GET/PUT/DELETE /api/profiles/{content_id}`, site-scoped to `auth.site_id` and to a `content_id` that must already exist for that site (`require_content_for_site()`, `src/api/profiles.rs:26`; `404` across sites, matching `/api/events/{content_id}/schedule`). `GET` is open to any authenticated caller (`get_profile()`, `src/api/profiles.rs:58`); `PUT` and `DELETE` require admin (`set_profile()`, `src/api/profiles.rs:70`; `delete_profile()`, `src/api/profiles.rs:84`). `PUT` also requires the content's type to carry `shape: "profile"` (`require_profile_content()`, `src/api/profiles.rs:39`), `422` on any other shape, since only a profile-shape type has this table's row.

A caller sets any of `role_title`, `email`, `phone`, `website_url`, `photo_media_id` (a `media_assets` id), `address_line`, `city`, `region`, `postal_code`, `country` (ISO 3166-1 alpha-2), `latitude` and `longitude`, all optional. `PUT` upserts: the first call creates the profile row, a later one replaces it in place (`Profile::upsert()`, `src/models/profile.rs`).

`GET /api/content?type=&country=&region=` narrows a profile-shape type's entries to an exact match on `content_profiles.country`/`.region` (`Content::list_by_type_with_profile_filters()`, `src/models/content.rs`), the same way `?min_price=`/`?max_price=`/`?in_stock=` narrow a catalog-shape type.

## Document shape: summary, cover image and head tags

Unlike `catalog`, `event` and `profile`, the `document` shape (the built-in `article` template, `src/content_templates.rs`) keeps its typed fields as plain columns on `content` itself rather than a side table, since a listing page needs to read them without a join: `summary TEXT`, `cover_media_id` (a nullable `media_assets` id), `meta_title TEXT` and `meta_description TEXT` (all default to empty/null; see `migrations/{postgres,sqlite}/20261002000001_content_document_fields.sql`).

`POST /api/content`, `PUT /api/content/{id}` and `POST /api/content/push` all accept `summary`, `cover_media_id`, `meta_title` and `meta_description` alongside the existing fields, for every content type, not only a `document`-shape one; a type that is not `document`-shape simply has no admin form field or template that reads them back. `GET /api/content` and `GET /api/content/{id}` return all four on every entry. On `PUT /api/content/{id}`, `cover_media_id` follows the same clear-vs-leave-unchanged rule as `pages.parent_id`: an absent key leaves it unchanged, `null` clears it, and a value sets it.

The admin item form shows a Document panel (summary, cover image media id, meta title, meta description) for any content type whose `shape` is `document`. `blog_article.html` renders `cover_media_id`'s resolved URL inside a `.post-image` wrapper when present; `meta_title`/`meta_description` are stored but not yet read by the render pipeline.

## Galleries: ordered, captioned media collections

A gallery is a `content` item whose type has `shape: "gallery"` (the built-in `gallery` and `portfolio` templates, `src/content_templates.rs`, `CATALOG`; `portfolio` adds `client`, `project_date` and a richtext `description`). `src/models/gallery.rs` and `src/api/galleries.rs` (mounted at `src/api/mod.rs:135`) add a `gallery_items` table of `(content_id, media_asset_id, position, caption, alt)` rows, keyed on `(content_id, media_asset_id)` and cascading with both the content and the asset. Unlike the one-to-one `content_events` and `content_profiles`, a gallery has many rows, so the whole ordered list is replaced at once.

`routes()` (`src/api/galleries.rs:82`) registers `GET` and `PUT /api/galleries/{content_id}/items`. `GET` is open to any authenticated caller (`get_items()`, `src/api/galleries.rs:48`); `PUT` requires admin (`put_items()`, `src/api/galleries.rs:60`). Both resolve the content through `require_gallery_content()` (`src/api/galleries.rs:27`): `404` for a `content_id` on another site, `422` when the content's type is not `shape: "gallery"`.

`PUT` takes a bare JSON array, `[{"media_asset_id", "caption"?, "alt"?}]`, and `position` is the array index. `GalleryItem::validate()` (`src/models/gallery.rs:103`) answers `422` for an asset that appears twice, does not exist, belongs to another site, or is neither `image` nor `video`; a rejected save writes nothing. `GalleryItem::replace()` (`src/models/gallery.rs:135`) deletes and re-inserts in one transaction. Both verbs return the saved items in order, each with `media_asset_id`, `url`, `kind`, `mime`, `position`, `caption` and `alt`.

### Embedding a gallery in a page

The `gallery_embed` widget (`src/widgets/gallery_embed.rs`) takes `gallery_id` and `layout` (`grid` or `carousel`; the carousel layout reuses the `carousel` widget's markup and leaves videos out). Media is public only while a published page references it, and a widget holding just a gallery id would leave every image unreferenced. So `PagePublication::upsert_from_draft()` calls `inline_gallery_items()` (`src/models/gallery.rs:238`), which writes the resolved items (`image`, `kind`, `alt`, `caption`) into each `gallery_embed` widget's config in the publication snapshot. `extract_media_references()` then finds the images with no gallery-specific code, and the public render reads no gallery rows. A widget with an empty, missing or other-site `gallery_id` publishes with no items and logs a warning.

Editing a gallery never publishes anything. An embedding page keeps its old snapshot until it is republished, and a republish after an edit stores a new revision. A draft or preview page has no inlined items, so `gather_widget_data()` (`src/render/service.rs:422`) resolves them into `WidgetData::galleries` before the synchronous render.

Deleting a media asset that a gallery holds is refused: the admin delete answers with an error naming the gallery (`GalleryItem::gallery_titles_using_asset()`, `src/models/gallery.rs`).

## The docs home widget

A docs site's landing page is a `docs_home` widget (`src/widgets/docs_home.rs`), set like any other through `PUT /api/pages/:id/widgets` or a pushed page tree. Its properties: `heading` (default the site name), `subheading`, `placeholder` (default "Search the docs"), `root_path` (the page whose direct children become product cards, default `/docs`), `recent_limit` (1 to 10, default 5), `id` and `section_class`. The product cards, page counts and recently updated pages are computed at render time from the published pages, so a pipeline sets nothing else; a product page's `meta_description` is its card summary when set. Pushed pages also get heading ids and a `page.outline` from their Markdown at publish.

## Importing WooCommerce product exports

`POST /api/import/woocommerce` (`src/api/import.rs`, mounted at `src/api/mod.rs:128`) reads a WooCommerce product CSV export and writes it onto a catalog-shape content type, the same shape `/api/products/*` already requires. Admin only. The handler itself only parses the multipart request; `apply_woocommerce_import()` (`src/import/woocommerce.rs:1067`) does the work and is what a test calls directly to exercise the import without going through HTTP.

Request is `multipart/form-data`:

- `file` (required): the CSV bytes.
- `type_slug` (required): the catalog-shape content type's slug. `422` if the type does not exist or is not `shape: "catalog"`.
- `mapping` (optional): a JSON `ColumnMapping` (`src/import/woocommerce.rs:53`) overriding one or more column names; any field left out falls back to the standard WooCommerce export header named below.
- `dry_run` (optional, `true`/`1`): plan the import and report it, writing nothing.
- `prune` (optional, `true`/`1`, default `false`): delete a product this source owns that the file no longer lists.
- `image_hosts` (optional): a comma-separated allowlist of hostnames an image URL may be fetched from. Required, and `422` without it, whenever the file names at least one image URL.

The default column mapping, each overridable by the matching `ColumnMapping` field:

| CSV column | Default WooCommerce header | Meaning |
| --- | --- | --- |
| `id` | `ID` | WooCommerce's own product/variation id, stored as `external_id` |
| `type_column` | `Type` | `simple`, `variable`, or `variation` |
| `parent` | `Parent` | A variation row's parent product, by `ID` or `SKU` |
| `title` | `Name` | Content title (variation rows have none) |
| `sku` | `SKU` | Product or variation SKU |
| `regular_price` | `Regular price` | Base price |
| `sale_price` | `Sale price` | Present and lower than `regular_price` becomes `compare_at_price_cents` (the regular price, shown struck through) with the sale price as `base_price_cents` |
| `stock` | `Stock` | `stock_quantity` |
| `status` | `Published` | `1`/`true`/`publish`/`published` -> `published`; `0`/`false`/`draft` -> `draft`; `archived` -> `archived`; absent -> `published` |
| `categories` | `Categories` | Comma-separated category terms (`taxonomy = "category"`); a `Parent > Child` WooCommerce path keeps only the leaf |
| `tags` | `Tags` | Comma-separated tag terms (`taxonomy = "tag"`), same leaf rule |
| `images` | `Images` | Comma-separated image URLs |
| `images_field` | (none; defaults to `images`) | The `content.data` key the fetched image URLs are written to, not a CSV column |
| `schema_fields` | `{"description": "Description", "short_description": "Short description"}` | Maps a `content.data` key to the CSV column that fills it |

A variation row's axis values are matched by attribute name (case-insensitive) against the content type's declared `schema.variation_axes` (`declared_variation_axes()`) whenever the file has `Attribute N name` columns; reading falls back to position, `Attribute 1 value(s)`, `Attribute 2 value(s)`, ... in declared-axis order, only when no `Attribute N name` column exists at all (`variation_axis_raw_values()`, `src/import/woocommerce.rs`). A variation is validated the same way a direct `POST /api/products/{content_id}/variations` write is (`validate_variation_axes()`), so a variation missing a value for a declared axis names the axis and fails the whole file.

Writes are idempotent, keyed on `(site_id, external_source, external_id)` with `external_source = "woocommerce"` (`EXTERNAL_SOURCE`, `src/import/woocommerce.rs:45`), the same keying `POST /api/content/push` uses (see "Pushing content from an external pipeline" above): re-running an unchanged file updates nothing, and changing a price on a re-run updates the same content row rather than creating a new one. `prune=true` deletes a content row this source owns that the current file no longer names; `products`, `product_variations` and `content_terms` rows cascade with it.

Validation runs over the whole file before anything is written: a malformed price, an unresolvable status, a variation whose parent is missing from the file, a duplicate SKU, and a schema violation all abort the entire import and report the offending row's number and, where known, its `external_id`, writing none of it (`RowValidationError`, `src/import/woocommerce.rs:119`); the response is `422`:

```json
{ "error": "validation_failed", "row": 3, "external_id": "12", "message": "..." }
```

An image is different: it is fetched only over HTTPS and only from a host named in `image_hosts` (`https_host()`, `src/import/woocommerce.rs:416`), stored through the same media pipeline an admin upload uses, and a failed fetch or a disallowed host is reported per row without failing that row's product write or the rest of the import (`RowFailure`, `src/import/woocommerce.rs:110`).

`dry_run=true` runs the same validation and planning and returns the same counts, plus `preview`: the first 20 planned rows, and writes nothing. A real run's response reports what happened:

```json
{ "created": 2, "updated": 0, "skipped": 2, "pruned": 0, "images_stored": 1,
  "failed": [{ "row": 5, "external_id": "9", "message": "image host 'cdn.example.com' is not listed in image_hosts" }],
  "preview": [] }
```

`skipped` counts variation rows, which are consumed by their parent product rather than becoming a content row of their own.

## Uploading media from a pipeline

`POST /api/media` (`upload_media()`, `src/api/media.rs:37`) lets a session or `sfk_` machine token upload a file into its own site's media library, admin or super_admin role. It shares the stage-validate-register pipeline the admin media library's cookie-only upload route (`media_upload()`, `src/admin/media.rs`) uses, through `crate::media::stage_uploaded_field` and `crate::media::register_uploaded_media` (`src/media.rs`), so the same filename, extension, size and rate limit rules apply here: the allowed extensions, the 100 MB cap, and 15 uploads per site per caller per 10 minutes.

The handler guards with `require_content_write()` rather than `require_admin()`, so a `content`-scoped `sfk_` token can upload here too: a docs or content pipeline that already holds that narrower credential to push pages and content types no longer needs a full-scope admin token just to attach an image. The role check is unchanged, so a content-scoped token still cannot upload anything its role could not, and it still reaches no other non-content route (`only_the_content_routes_accept_a_content_scoped_token`, `src/auth/middleware.rs`).

Request is `multipart/form-data`:

- `file` (required, exactly one): the upload. A missing or empty-filename `file` part is `400`.
- `path` (optional): the destination folder, as a media library virtual path (for example `Images/Products`). Defaults to the library root. A path naming another site's `Sites/{slug}` branch, or containing `..`, is `400`/`404` the same way the admin upload route's own path rejects one.

Response is `201` with the asset:

```json
{ "id": "...", "path": "Images/logo.png", "url": "/media/...", "kind": "image", "mime_type": "image/png" }
```

A token or session is scoped to exactly one site, so the request has no field that can name a different site's library; the caller's own site is the only one `normalize_media_library_path` is ever given to match against.

When the server cannot create the site's media folder because of file permissions, the upload answers `503` with an `error` naming the cause (media storage is not writable) rather than a bare internal error; the raw I/O error goes to the server log only.

## Sign-ins held for approval

With the sign-in approval gate on (`LOGIN_APPROVAL_ENABLED=true`), `POST /api/auth/setup` and `POST /api/auth/login` can answer `202 Accepted` with no token: the sign-in is held until the account owner opens the emailed approval link. API sign-ins are held on the new-country trigger only; the new-device trigger is browser-only, because an API client has no cookie jar and holding it on that basis would be a permanent lockout for automation. The body carries the handle to wait on:

```json
{
  "approval_required": true,
  "claim_reference": "<64 hex chars>",
  "poll_path": "/api/auth/login/approval/<claim_reference>",
  "expires_in_minutes": 15,
  "message": "This sign-in is from a new location. ..."
}
```

`GET /api/auth/login/approval/{claim_reference}` then reports that one sign-in, and hands over its session once the owner has approved. Every answer carries a `status`:

| Status | HTTP | Meaning |
| --- | --- | --- |
| `pending` | 202 | Not approved yet. `expires_at` is when waiting stops being useful. |
| `approved` | 200 | The owner approved; `token` is the session JWT, returned exactly once. |
| `already_collected` | 410 | A previous poll took the session. Sign in again for a new one. |
| `expired` | 410 | The hold reached its 15-minute expiry. Sign in again. |
| `not_found` | 404 | No held sign-in matches that reference. |

The claim reference is not a credential: it can only be read, never approved with, and the poll hands out a session only after the emailed link has been opened. Both the reference and the approval token are stored as SHA-256 only. Poll no faster than once every 5 seconds: the endpoint is rate limited to 120 requests per IP per 10 minutes. The hold lasts 15 minutes; after that, sign in again, which succeeds from the same country because approval recorded it as one the account has used.
