# Saved-draft lifecycle and existing media library

Revision4 extends the root-accepted local UI contributor `54e2680056aa0260c7e892ef3449e7c49f0288d0`
in the same editor-owned checkout. The feature remains disabled by default,
requires an explicit company allowlist and existing newsletter permissions, and
does not change the legacy editor, existing newsletters or company rollout.

## Restore and saved copies

`POST /newsletter-editor/drafts/{draft}/restore` takes the current `revision`
and historical `source_revision`. It requires the original page's encrypted
actor/company context and edit permission. The company retention lock and a
transaction protect the current draft; stale revisions return409. The selected
snapshot must belong to that same tenant-scoped draft. Its JSON is validated
and compiled with the current renderer, including current media ownership and
availability. The operation appends a new revision; neither historical JSON nor
historical HTML/pipeline artifacts are rewritten. Missing/invalid snapshots,
deleted library assets and compilation failures leave the current state intact.

The UI names the version being restored and explains the new-version result.
Unsaved changes require an explicit discard checkbox. Editing again invalidates
that acknowledgement. Cancel preserves edits. Edits made while a restore is in
flight are retained locally against the newly acknowledged server revision.
An ambiguous restore response blocks further mutations until reopening the
saved draft; it cannot silently replace the user's local state.

`POST /newsletter-editor/drafts/{draft}/duplicate` additionally requires create
permission, an explicit copy name, the source's current revision and a UUID
`intent_id`. It copies the **saved** JSON after current validation/compilation,
creates an independent draft at revision1 and leaves the source untouched.
Caller content, company, actor and compiled artifacts are never trusted. The
additive `newsletter_editor_copies` table binds the intent to company, actor and
request fingerprint. A repeated identical intent returns its original copy;
changed parameters for the same intent return409. The company lock is shared
and protects retention, not intent serialization. Source row locking and the
unique intent constraint prevent duplicate committed copies; a concurrent
constraint conflict rolls back the entire copy transaction and may require
reopening after an ambiguous response.
This has local SQLite coverage, not a MySQL concurrency qualification.

The UI explicitly says that unsaved source changes are excluded. It opens the
copy through a separate link while keeping the current page and edits. Busy
guards prevent overlapping mutations. A malformed successful response or an
uncertain network/server result latches copy retries; an independent source
save remains possible. Definite rejections require another explicit action,
and session-token refresh never replays a write automatically.

## Read-only existing media selection

The recovered library contract is the legacy `Media` and `Folder` model,
`mediaIndex`/`mediaShow` permissions and authenticated `/media/image/{id}` route.
It is separate from the newer `MediaItem` provider. The existing unbounded
legacy endpoint remains unchanged. The new bound-context
`GET /newsletter-editor/media` returns at most20 own-company raster images per
request, with an ID cursor, bounded literal search and optional own-company
folder. Invalid rows still advance the bounded page cursor.

The server derives canonical HTTPS URLs from configured `app.url`, descriptions
from the existing media description, and dimensions/MIME/size from actual file
headers. PNG/JPEG/GIF/WebP are allowed. Soft-deleted rows, foreign folders,
unsafe names/paths, symlink escapes, malformed images and oversized files are
excluded. Saves, previews, restores and copies revalidate references to this
application's library route. Alternate ports, trailing-dot hosts, traversal,
queries and noncanonical URLs do not bypass that boundary.

The SDK media provider exposes selection only: upload, edit, replace, delete,
folder mutations, remote imports, usage and storage operations are disabled.
No new upload, remote fetch/proxy, provider, credential or external account was
added. The SDK reduces selected assets to URL and description, which is why
the server also validates library references on every compilation.

The pinned source remains Templatical v0.46.0 at
`22f9c68ab10e09058437d4085fdef05e2175bfe0`, under the existing FSL-1.1-MIT
additional embedding permission. In addition to the existing531 editor keys,
`locales/sv-media.json` and generated `sv-media.ts` supply91 media keys. The
tracked fifth patch is additive; English is retained. `prepare-source.mjs`
fails for missing text, key/interpolation mismatch or unexpected source edits.
Build instructions and license custody remain in `newsletter-editor-ui-3967.md`.

The host build removes obsolete hashed assets only inside its canonical,
exclusively generated `public/newsletter-editor` directory after a successful
build. It rejects symlinks and unknown file types, retains the current esbuild
output graph and full license, and preserves unrelated Mix manifest entries.
Repeated source builds therefore do not accumulate old editor implementations.

## Local verification and boundaries

Run PHP's focused Draft/Lifecycle/Media tests and the renderer Node tests.
`NUHET_EDITOR_VERIFY_LIFECYCLE=1 NUHET_EDITOR_VERIFY_LOCALE=sv` (or `en`)
with `node tools/newsletter-editor/verify-native.mjs` exercises actual mounted
controls and real local Laravel file sessions/cookies/CSRF. Login bootstrap is
synthetic; it does not prove production login. Every configured database alias
and actual PDO is checked against the uniquely marked disposable SQLite file
before fixture writes. Media, sessions, views and local/newsletter disks are
inside the same exact owned root. Unrelated mutations and external browser
network requests are blocked. The finite harness closes its browser/process and
removes only its own marked directory, then records absence.

Full legacy and v2 `/newsletter` entry routes use actual production controllers,
models and layouts against empty synthetic newsletter fixtures. SQLite's `IF`
function and statistics schema metadata are fixture compatibility only; the
real PDO target is checked before setting schema name `main`. These local
empty-list checks do not prove all legacy JavaScript or populated customer data.

For genuine before captures, the same fixture router serves a separate owned
detached accepted54 checkout with its exact original146 build files and private
dependencies. `NUHET_EDITOR_VERIFY_BEFORE=1` selects only that baseline. It does
not hide new controls with CSS or manufacture screenshots from an error page.
The baseline is retained read-only until evidence consumers release it.

Library URLs remain HTTPS in persisted JSON and compiled output. The owned
HTTP-only preview maps only its own HTTPS image URLs in Playwright to the real
loopback media controller. This test-only TLS substitution is disclosed in each
receipt; it proves controller/bytes and UI selection, not production TLS,
public email delivery or a production proxy.

A separate `NUHET_EDITOR_VERIFY_TLS=1` check uses a disposable one-day self-signed
certificate and an owned loopback HTTPS front end with ordinary browser cookies.
It performs no image credential/response substitution. This found that an opaque
sandbox origin redirected private images to login. The saved preview now allows
the application origin in both iframe and CSP sandbox while still forbidding
scripts, forms, top navigation and all other default resources. The exact saved
HTML remains unchanged. A supplemental hostile-body probe retains the actual
controller CSP and Blade iframe and verifies blocked script access to the parent,
form POST and top navigation. Self-signed local TLS is not external TLS proof.

Existing media deletion soft-deletes its row and renames files with a `.del`
suffix; folder paths can move. These private saved-draft references therefore
are not immutable delivery assets. Publication must separately copy/retain
authorized assets, preserve output/merge/GDPR/tracking contracts, and qualify
deletion/retention with the new intent table. No production migration is run.
Also open are shared publication, actual Nuhet templates/social/video, byte
equivalence, real email-client/dark/blocked-image rendering, MySQL, final phone
authoring/product choice, pilot and release. Phone remains saved-preview/status
with the SDK's normal larger-screen notice. This unit cannot close the card.

Compiler image sources and placeholders must already be canonical WHATWG HTTPS URLs; browser-normalized host/path aliases are rejected before persistence. Canonical external HTTPS image URLs remain supported.
