Docker-only admin
The portfolio admin UI runs only via the standalone Docker admin stack. It is not bundled into @tgmc/web, npm run dev, or AWS Lambda.
Package README: core/admin/README.md · Layer: packages/web-layer-admin/README.md
Why a separate app
- Separation: The standalone admin UI and layer routes are not bundled into the public Lambda. Public web media APIs still use an admin-token runtime setting and server-side gate.
- Local tooling: MinIO emulates S3/CDN for all environments without touching AWS.
- One UI, three stores: SQLite, Postgres, and DynamoDB Local run side by side; the nav selector picks which backend to CRUD.
Architecture
Current admin process UML and traceability (October 21 source review). The October 14 snapshot is historical; target architecture separates proposed work from implementation.
flowchart LR
subgraph host["Host (127.0.0.1)"]
Browser["Browser :4400"]
end
subgraph stack["tgmc-admin Compose"]
Admin["admin\n@tgmc/admin"]
SQLite["SQLite\n./data/admin.sqlite"]
PG["postgres :5432"]
DDB["dynamodb-local"]
MinIO["minio :9000"]
end
Browser --> Admin
Admin -->|db=sqlite| SQLite
Admin -->|db=postgres| PG
Admin -->|db=dynamodb| DDB
Admin --> MinIO
Admin -.->|sync read-only| Output[".output/{local,development,test}/public"]
| Piece | Path |
|---|---|
| App | core/admin (@tgmc/admin) |
| Layer | packages/web-layer-admin |
| Compose | docker/docker-compose.admin.yml |
| Helper | scripts/docker-admin.mjs |
| Env | .env.admin.example → .env.admin |
Surfaces
| Route | Purpose |
|---|---|
/admin |
Sign in with ADMIN_TOKEN (session) |
/admin/blog |
Blog CRUD (from @tgmc/web-layer-admin) (list, editor) |
/admin/messages |
List/delete contact messages |
/admin/cdn |
List/upload/delete/sync assets in local MinIO |
/admin/media |
DAM: upload, preview grid, drawer, variants |
/admin/slots |
Media slots: library asset, static path or placeholder per slot (slots) |
The media page asks for a title and alt text before an upload, and the drawer edits them and renames files (see Local media library).
- Layout. Pages use the theme’s
.page-with-navwithout a side nav, socore/admin/assets/css/admin.scssmakes the body span the whole row (the theme would put it in the narrow nav column). - Navigation.
AdminNavmarks the current section witharia-current="page"and an underline plus weight (not colour alone), including nested routes such as the blog editor (app/utils/admin-nav.ts). Each link is at least 44px wide and tall (touch-target($square: true)), so short labels such as “CDN” still meet the touch floor. - CDN page. Upload and sync report their result (“Uploaded …”, “Synced N file(s) from …”) after the list reloads; uploads are base64-encoded in chunks (
app/utils/base64.ts), so large files work. Choosing a file fills Object key with its name unless you typed a key yourself (app/utils/upload-key.ts), and the form clears after each upload, so the next upload never reuses (and overwrites) the previous key. The object table scrolls inside its own labelled, keyboard-focusable box, never the page; Delete leads each row and is named after its object, and each row’s key is its row header. After a delete, focus moves to the next row’s Delete (else the previous one, else the status line). Delete is immediate (no Undo yet — see the TODO). - Form labels. Every
label(for=…)names a control in the same file (core/admin/tests/admin-form-labels.spec.ts).UiInputText,UiTextarea,UiPasswordandUiSelectput the id on the form control whether it comes frominput-id,#idorid="…";input-idwins when both are set, and PrimeVue’s wrapper never gets the id (packages/nuxt-layer-ui/tests/ui-control-id.spec.ts). PrimeVue’s select control is a<span role="combobox">, which a label click can’t focus natively, soUiSelectforwards clicks on itslabel[for]to it. Inside aUiFormFieldevery control, the select included, is also named byaria-labelledby.
Blog editor
/admin/blog/new and /admin/blog/:id are one page, packages/web-layer-admin/app/pages/admin/blog/[id].vue. It is the reference page for the forms template (UI components § Forms) and validates with the shared schema packages/web-layer-admin/shared/blog-schema.ts, the same one the server uses (owner Q1 A).
- Fields. Title, Slug, Excerpt, Body (hint “Markdown”) and Status, with the ids
#post-title,#post-slug,#post-excerpt,#post-bodyand#post-statusin the form#post. Title, Slug and Body are required. On a new post the slug follows the title until you edit it by hand. A slug typed with capitals or spaces passes and is normalised (normalizeSlug), on the client and on the server. - Cover and Insert media (
AdminBlogMediaFields, planner’s call 10). The page renders the component after Body with props{ coverAssetId, coverAlt, bodyRef }and the eventsupdate:coverAssetId,update:coverAltandinsert(text); the form holds the values (coverAssetIdandcoverAltare inFIELDS,EMPTY_POSTandtoFormValues). The layer ships a fallback with plain Cover asset id and Cover alt text inputs (#post-coverAssetId,#post-coverAlt; an empty id isnull) and no picker.core/admin/app/components/AdminBlogMediaFields.vueoverrides it: the app’s component dir wins over the layer’s (checked with an isolatednuxi prepareof core/admin:components:extendlists only the core/admin file).core/admin/tests/admin-blog-media-fields-override.spec.tsguards it: the generatedcore/admin/.nuxt/components.d.ts(fromnuxt prepare core/admin, the rootpostinstall) must mapAdminBlogMediaFieldsto the core/admin file.- Cover. Choose cover opens
AdminMediaPickerover image and SVG (“Choose a cover”). The field shows a preview (previewUrl, hidden from assistive tech because the name beside it says the same) and “Current:", looked up through `GET /api/admin/media/assets/:id` for a saved cover; an id the library doesn't know shows "(not found in the library)". **Clear** sets `coverAssetId` to `null` and keeps focus on **Choose cover**. As on the slots page, the field label names a `role="group"`, and **Choose cover** carries the field's `aria-invalid`. Choices and Clear are announced ("Save to apply it."). - Cover alt text. Trimmed by the schema, and a blank alt saves as
null, so the cover uses the asset’s own alt (plan 3, T4-3). - Insert media opens the picker over every kind and writes a block reference at the body’s caret; with a selection it inserts after the selection, and nothing is deleted. The reference is
for an image or SVG,::media{asset=<id> alt="<alt>"}otherwise (mediaReferenceincore/admin/app/utils/blog-media.ts, overbodyMediaReferenceincore/web/shared/media-refs.ts, next to the parser). The alt is the asset’s own (empty when decorative), on one line, without[ ] ( ) { } \and with"as'(referenceAlt), so it can’t end early or smuggle in another reference:splitBodyMediareads back exactly one media segment andextractAssetRefIdsexactly one id (round trip incore/web/tests/media-refs-shared.spec.ts). The page puts it on its own line with a blank line before and after (insertBlock,packages/web-layer-admin/app/utils/blog-body-insert.ts) and leaves the caret after it. Where the browser supports it the text is typed withdocument.execCommand('insertText')into the focused body, so Ctrl+Z / Cmd+Z undoes it; otherwise the value is set (no native undo). Focus returns to Insert media (aria-controls="post-body"), which announces “Insertedinto the body.". A video or audio inserts with the warning "No captions yet: this video will play without captions." ("this audio" for audio), shown under the button and in the same announcement; it never blocks (owner, 2026-10-23).
- Cover. Choose cover opens
- Save is the one primary action. A failed save lists the problems in the error summary and focuses the first invalid field. A 422 or 409 from the server lands on the fields (a slug conflict on Slug), a 404 or 400 lands in the summary, and a server failure without a payload shows “Save failed.” there. A 401 signs out with no message on the form.
- After a save the page rebases each field on the values the server returned, so “Post saved.” shows in the actions row and is announced. After a create it resets the form to the created post and goes to
/admin/blog/<id>; “Post created.” is announced, but the new page doesn’t show it (see the TODO). - Unsaved changes. Back, a nav link or a breadcrumb with unsaved changes opens the in-page “Leave without saving?” dialog (Stay / Leave). Reload or closing the tab gets the browser’s own prompt. The page doesn’t ask on the sign-in redirect after a 401, after a delete or after a create. Switching the database in the header reloads the post and still drops unsaved edits without asking (see the TODO). Admin dialogs sit on the solid
--theme-surface-color(core/admin/assets/css/admin.scss): the theme’s glass panel over the opaque mask left their text below 4.5:1. - Delete (edit page only) confirms in place with the kit’s
UiConfirmInline(owner Q2 A). “Delete…” asks “Delete “”?" (or "Delete this post?" when the saved title is empty; owner Q4 A) with Delete and Cancel. The question uses the saved title, not unsaved edits. Focus moves to Cancel; Cancel or Escape returns it to "Delete…". There is no `window.confirm`. Delete returns to the list, which runs the 8 s Undo window and the real `DELETE` (owner Q1 A): the editor hands the post over in memory (`useState` key `BLOG_DELETE_HANDOFF`, stamped with the time, never a URL parameter, so a link can't delete a post). If the navigation doesn't reach the list (cancelled, or redirected to sign-in), the editor takes the handoff back, the unsaved-changes guard is on again, "Post not deleted." is announced and focus returns to "Delete…".
Blog list
/admin/blog (packages/web-layer-admin/app/pages/admin/blog/index.vue) lists posts through the kit’s useCrudResource over adminBlogAdapter (packages/web-layer-admin/app/utils/admin-blog-resource.ts); the API returns every post at once, so there is no Load more. Switching the database in the header commits pending deletes and reloads the list.
- Status filter. All / Drafts / Published is a button group with
aria-pressed(owner Q9 A), kept in the URL as?status=draft|published(useRouteQueryStatewithblogListCodec; owner Q7 A). Unknown values fall back to All. A filter change replaces the history entry, so a reload or a shared link keeps the filter and Back leaves the list. - Needs media filter. Any media / Needs media is a second
aria-pressedbutton group beside the status filter, kept as?media=needs(planner’s call 14). Needs media lists the published posts whoseneedsMediais set byGET /api/admin/posts(drafts are never flagged), whatever the status filter (filterBlogPosts). A flagged row says “Needs media” with an icon, in text. A filter change announces the result once the list has loaded (“2 published posts need media.”, “3 draft posts.”, or the empty text;blogListResultText). An empty list says what the filters found (blogListEmptyText): “No published posts need media.” under Needs media (even with no posts at all), “Only published posts are flagged: no drafts need media.” with Drafts, “No posts yet.” for an empty database, else “No draft posts.” / “No published posts.”. - Delete with Undo. A post handed over by the editor disappears from the list and
UiUndoNoticeoffers Undo for 8 s (“Deleted “”.", or "Deleted this post." when the title is empty); Undo puts it back and focuses its link. Leaving the page or switching the database commits at once. The `DELETE` goes to the database the delete was confirmed in: `adminFetch` keeps an `X-Admin-Database` header the caller set. A failed delete restores the post and shows the error above the list in a `UiMessage`, which is its own live region (`role="alert"` with PrimeVue), so the page does not announce it a second time. The error and the Undo line render outside the list's load-error branch, so they show even when the list failed to load. - Nothing is deleted without the Undo window. The list decides with
decideDeleteHandoff(admin-blog-resource.ts): a post it shows gets the Undo window; if the list failed to load, “Post not deleted: the list didn’t load.” is shown and announced; if the post isn’t in the list (or the header now shows another database), “Post not deleted: it isn’t in this list.” is shown and announced. A handoff already older than 10 s (BLOG_HANDOFF_MAX_AGE_MS) when the list page opens (the age is taken at arrival, so a slow list load never drops a delete the user just confirmed), a list load that failed with a 401 (the sign-in redirect takes over), and a handoff the list never took (left before it loaded) are dropped silently. - Database switch. While the list reloads, it shows “Loading…” instead of the previous database’s rows.
Database selection
Use the Database dropdown in the admin nav. Values are database backends, not SYS_ENV stack names:
| UI value | Backend | Data location |
|---|---|---|
sqlite |
SQLite | ./data/admin.sqlite (host volume) |
postgres |
PostgreSQL 16 | tgmc-postgres-admin container |
dynamodb |
DynamoDB Local | tgmc-dynamodb-admin volume (persists), portfolio-admin-* tables incl. Media |
- Stored with the token in the admin session (
tgmc-admin-session, see Session). - Sent on every admin API call as
X-Admin-DatabasebyadminFetch. - Server may also accept
?db=sqlite|postgres|dynamodbon admin APIs.
Internally, stores still use the existing adapters. The selection is passed to the store factories as an explicit dataBackend, so it wins over any DATA_BACKEND in the admin container’s environment and over the SYS_ENV default (development now defaults to DynamoDB). SYS_ENV is only used to pick the CDN sync output dir:
| Database | Store dataBackend |
CDN sync output dir |
|---|---|---|
sqlite |
sqlite |
.output/local/public |
postgres |
postgres |
.output/development/public |
dynamodb |
dynamodb |
.output/test/public |
Session
The admin session belongs to one browser tab. It is a single sessionStorage key, tgmc-admin-session, holding { v: 1, token, database }. It is cleared when the tab closes, and a tab opened from the address bar starts signed out. A duplicated tab, or one opened from an admin page, can start with a copy of the session (browsers copy sessionStorage to such tabs); after that the two copies change independently.
- One owner.
useAdminSession()(packages/web-layer-admin/app/composables/useAdminSession.ts) is what pages and components use. It returnstoken,database,databaseLabel,signedIn,signIn,signOutandsetDatabase, and it writes every change. Theadmin-session.clientplugin also touches the key: it loads it withloadAdminSession(which can rewrite it while converting the old keys) and clears the token throughsignOutafter a401. Pages and components never read or writesessionStoragethemselves; the pure storage helpers live inapp/utils/admin-session.ts. - Loaded once. The
admin-session.clientplugin reads the key before the first render. After that, every change updates memory first and then writes the key. When the visitor is signed out and on the default database (sqlite), the key is removed. - Old keys. The earlier
portfolio.adminTokenandportfolio.adminDatabasekeys are converted once: the new key is written before the old ones are removed. Iftgmc-admin-sessionalready exists, the old keys are just removed. - Blocked storage. If
sessionStorageis blocked or full, the session stays in memory, so sign-in still works until the page reloads. - Client-rendered routes. Because the session only exists in
sessionStorage, the layer’snuxt.config.tssetsrouteRuleswithssr: falsefor/adminand/admin/**. Server-rendered HTML would always be signed out and would not match the page after hydration. - Clear saved token on the sign-in page signs out but keeps the selected database.
- Token check. Continue sends the token to
GET /api/admin/session(verifyAdminTokeninapp/utils/admin-fetch.ts) before saving it; the button reads “Checking…” meanwhile. A rejected token (401) shows the server’s reason when it gives one — “Admin writes are disabled (ADMIN_TOKEN not configured)” on a stack without a token, “Admin access is disabled: ADMIN_TOKEN is a placeholder or shorter than 32 characters” on one with a weak token — and otherwise “That token is not valid for this environment.”; focus returns to the field and nothing is saved. A server error reads “The admin server failed (5xx: …) — check its logs, then try again.”; no response reads “Could not reach the admin server — try again.” (copy:app/utils/admin-sign-in-messages.ts). - Token compare. The server compares SHA-256 digests of the sent and expected tokens with
timingSafeEqual, so neither the answer nor its timing reveals the token’s length (server/utils/admin-auth.ts).
Token strength and Host check
- Weak tokens are refused (review I8). Outside unit tests the server treats a weak
ADMIN_TOKENlike a missing one: a placeholder (change-me…), a value committed to this repo (the olddocker-test-admin-token), or anything under 32 characters (adminTokenWeakness/usableAdminTokeninpackages/web-layer-admin/server/utils/admin-auth.ts). Every admin route, the session check included, then answers 401 with that reason, even for a matching Bearer, and so does the web’s/api/media/*for the admin principal..env.admin.exampleshipsADMIN_TOKEN=empty; generate one withopenssl rand -hex 32. The token is runtime-only:core/admin/nuxt.config.tssetsruntimeConfig.adminToken: ''and never reads it at build, so.output/adminnever contains it (the server readsNUXT_ADMIN_TOKEN/ADMIN_TOKENfrom the container env). - Host allowlist (
server/middleware/host-allowlist.ts,server/utils/admin-host.ts). The admin listens on127.0.0.1:4400, but a page on another site can reach it through DNS rebinding (its own hostname resolving to 127.0.0.1); the browser then sends that hostname asHost. Every request whoseHostis not a loopback name (localhost,*.localhost,127.0.0.1,[::1], any port), anADMIN_ALLOWED_HOSTSentry (comma-separatedhostfor any port, orhost:port) or the specificHOST/NITRO_HOSTis a 403 “Host not allowed” before any route runs. A request withoutHost(no browser sends one) passes.
Admin requests
Use useAdminFetch() (the plugin’s $adminFetch) instead of $fetch with hand-built headers. It is client-only and throws if the plugin has not run.
- Each request gets
Authorization: Bearer <token>(when signed in) andX-Admin-Database: <database>, read from the in-memory session rather than from storage. - Requests to other origins never get these headers. The request URL, its
baseURL, and the URL built from both must all stay on the page’s origin. - A
401signs out and sends the visitor to/admin?expired=1&redirect=<current page>. The sign-in page shows “Session expired — enter the token again.”, moves keyboard focus to the token field, and, after the token is entered, returns the visitor to that page. When several requests fail at once, they share one navigation. - On the sign-in page itself, a
401only clears the token; it does not navigate. - A stale
401is ignored. If the request was sent with a different token (or none) than the session now holds, the token entered since stays signed in. - The caller still receives the original
401error.
Guarded pages and redirects
- Token-gated pages declare
definePageMeta({ middleware: 'admin-auth' }): the blog list and editor, messages, CDN and media pages. When admin writes are enabled and nobody is signed in, the middleware sends the visitor to/admin?redirect=<page>. It skips the sign-in page and does nothing on the server. - After sign-in,
?redirect=is followed only when it is a same-origin/admin/…path other than the sign-in page, checked after..segments are resolved. Backslashes, whitespace and control characters are rejected. Anything else goes to/admin/blog. Theredirectadded after a401follows the same rule. - The media page uses
@tgmc/media-clientwithgetToken: () => token.valuefromuseAdminSession(). A401while loading the list (or the next page), uploading, saving details or renaming signs out and goes to the expired sign-in page; its other calls (detail, tags, variants, Re-run processing, delete) do not handle401yet (see the TODO).
Tests: cd core/web && npx vitest run tests/web-layer-admin.
Commands
cp .env.admin.example .env.admin # set ADMIN_TOKEN
npm run docker:admin # all DBs + MinIO + admin :4400
npm run docker:admin:down
npm run docker:build:admin # image build only
npm run build:admin # Nuxt build → .output/admin
Open http://127.0.0.1:4400/admin after healthchecks pass.
docker:admin with --build prepares .output/local, .output/development, .output/test, and .output/admin via scripts/prepare-nitro-output.mjs so CDN sync and the admin image have staged assets. It only builds an output that is missing: an existing .output/admin is copied into the image as-is, so run npm run build:admin after pulling admin or dependency changes (otherwise the image keeps the old build — see Troubleshooting).
Environment variables
Copy .env.admin.example to .env.admin. Required for writes:
| Variable | Purpose |
|---|---|
ADMIN_TOKEN / NUXT_ADMIN_TOKEN |
Shared secret for Bearer auth |
ADMIN_SQLITE_DATABASE_URL |
e.g. file:/app/data/admin.sqlite |
ADMIN_POSTGRES_DATABASE_URL |
e.g. postgres://portfolio:portfolio@postgres:5432/portfolio_admin |
DYNAMO_TABLE / NUXT_DYNAMO_TABLE |
Messages table (default portfolio-admin-Messages) |
DYNAMO_POSTS_TABLE / NUXT_DYNAMO_POSTS_TABLE |
Posts table (default portfolio-admin-Posts) |
AWS_REGION |
DynamoDB region (default us-west-2) |
AWS_ENDPOINT_URL |
http://dynamodb:8000 inside Compose |
DEFAULT_ADMIN_DATABASE |
UI default (sqlite in code; the Docker stack sets dynamodb) |
ADMIN_DATABASES |
Comma list enabled in UI |
S3_BUCKET |
MinIO bucket (default portfolio-assets) |
MINIO_ROOT_USER / MINIO_ROOT_PASSWORD |
MinIO credentials |
MEDIA_LOCAL_ROOT |
Local DAM SQLite/blobs root (default /app/data/admin-media) |
MEDIA_API_URL |
Optional forward target for portfolio /api/media/* |
MEDIA_API_TOKEN |
Bearer for remote media API (falls back to ADMIN_TOKEN) |
NUXT_PUBLIC_SITE_URL / SITE_URL |
Public site origin for the media drawer’s Used by links; unset: only MEDIA_API_URL’s origin |
MEDIA_API_TIMEOUT_MS |
Forward mode: timeout of each web API call (default 60000; then 504) |
MEDIA_API_UPLOAD_TIMEOUT_MS |
Forward mode: timeout of the presigned PUT, complete and ingest/svg (default 600000; then 504) |
MEDIA_PUBLIC_BASE_URL |
Optional base for local DAM media URLs (default same-origin /m/…) |
Ports (host bindings, all 127.0.0.1):
| Port | Service |
|---|---|
4400 |
Admin UI |
4410 |
MinIO S3 API (public bucket) |
4411 |
MinIO console |
5433 |
Postgres (optional host access) |
8001 |
DynamoDB Local (optional host access) |
Admin API
All routes require Authorization: Bearer <ADMIN_TOKEN> unless noted. Include X-Admin-Database (or ?db=) for data-backed routes.
| Method | Path | Database-aware |
|---|---|---|
GET |
/api/admin/session |
No — { ok: true } for the admin token, else 401; always Cache-Control: no-store |
GET |
/api/admin/posts |
Yes (local mode; forward mode ignores it) |
POST |
/api/admin/posts |
Yes (local mode; forward mode ignores it) |
GET |
/api/admin/posts/:id |
Yes (local mode; forward mode ignores it) |
PUT |
/api/admin/posts/:id |
Yes (local mode; forward mode ignores it) |
DELETE |
/api/admin/posts/:id |
Yes (local mode; forward mode ignores it) |
GET |
/api/admin/messages |
Yes |
DELETE |
/api/admin/messages/:id |
Yes |
GET |
/api/admin/cdn/objects |
No (MinIO only) |
PUT |
/api/admin/cdn/objects |
No |
DELETE |
/api/admin/cdn/objects?key= |
No |
POST |
/api/admin/cdn/sync |
Yes (picks .output/<sysEnv>/public from selected DB) |
GET |
/api/admin/cdn/sync |
Yes (reads persisted progress for the selected output directory) |
GET |
/api/admin/media/assets |
No (local DAM or MEDIA_API_URL) |
POST |
/api/admin/media/assets |
No (base64 JSON; per-kind byte cap, 413 too_large) |
GET |
/api/admin/media/limits |
No — { maxBytes: { image, svg, audio, video, model, document } } |
GET |
/api/admin/media/assets/:id |
No |
PATCH |
/api/admin/media/assets/:id |
No (title / alt / description / credit / tags; 400 invalid_meta) |
POST |
/api/admin/media/assets/:id/rename |
No ({ filename }; 409 name_conflict with a suggestion) |
DELETE |
/api/admin/media/assets/:id |
No (?force=1; 409 in_use with the pages using it) |
GET |
/api/admin/media/assets/:id/usage |
No — { assetId, pages }, the published pages that use the asset |
POST |
/api/admin/media/assets/:id/materialize |
No |
POST |
/api/admin/media/assets/:id/process |
No (Re-run processing) |
GET |
/api/admin/media/jobs/:id |
No |
GET |
/api/admin/media/slots |
Local mode — { slots: Array<{ record, view, needsMedia, seed }> } |
PUT |
/api/admin/media/slots/:id |
Local mode — the saved slot; 422 { code: 'VALIDATION', fieldErrors }; 404 |
POST |
/api/admin/media/slots/:id/reset |
Local mode — the slot reset to its JSON seed; 404 without a seed |
POST |
/api/admin/media/usage/rebuild |
Local mode — RebuildUsageResult; 503 when the local library cannot open |
Media delete, force and usage. DELETE /api/admin/media/assets/:id refuses an asset a published page uses: 409 data: { code: 'in_use', pages } (every page, { pageType, pageId, pageLabel, url, state }) and nothing is deleted. ?force=1 deletes it anyway; ?force=0 or no query do not force, and any other value (a bare ?force, true, a repeated param) is a 400 force must be 1 before anything is read (parseForceQuery from @tgmc/media, the web route’s parser). It answers { deleted, forced }; errors go through mediaErrorToHttp (local 409 in_use, 404 unknown asset). GET /api/admin/media/assets/:id/usage answers { assetId, pages } ([] when none; 404 unknown asset). POST …/:id/rename answers the asset plus usedBy: the pages whose stored /m/ URLs stopped working, null when they could not be read after the rename (the rename stands; logged locally as media.rename_usage_failed). In forward mode these call the web’s DELETE /api/media/assets/:id[?force=1], GET …/usage and rename routes (media-nuxt); a web 409 in_use reaches the page as the same 409 with its pages (statusMessage “Media asset in use”), and a web 403 admin_only (a tenant MEDIA_API_TOKEN asking to force) stays a 403 with its data, not the token 502 (see the forward-mode paragraph under Local media library). The media page’s Used by list, Delete anyway step and rename warning are under Local media library § Used by, refusal and Delete anyway.
Forward mode
With MEDIA_API_URL set, the admin keeps no post, slot or usage data of its own: it forwards to the web write endpoints with the admin server’s token (forwardToWeb in server/utils/media-service.ts, Bearer MEDIA_API_TOKEN or ADMIN_TOKEN), and the web records the media usage. Without it (local mode) the admin runs the same store code itself.
| Admin route | Forward mode | Local mode |
|---|---|---|
/api/admin/posts… |
/api/blog/posts… (the selector is ignored) |
The selected database’s post store; usage on the admin’s library |
GET /api/admin/media/slots |
GET /api/media-slots/records |
The selected database’s slots (createMediaSlotStoreForDatabase), views from the library |
PUT /api/admin/media/slots/:id, POST …/:id/reset |
PUT /api/media-slots/:id, POST …/reset |
saveMediaSlot / resetMediaSlot on that slot store, usage on the admin’s library |
POST /api/admin/media/usage/rebuild |
POST /api/media-usage/rebuild |
rebuildMediaUsage over the selected database’s posts and slots |
needsMedia.GET /api/admin/postsrows carry it in both modes: forwarded from the web’s list, or computed locally bypostsNeedingMediaon the admin’s library and the selected database’s slots (withLocalNeedsMediainserver/utils/admin-media-slots.ts, resolved uncached so a fresh upload counts at once).- Errors.
forwardToWebkeeps the media forward rules (timeouts 504, a 401 / 403 is the token 502, the upstream body only in the server log) and passes a 422 or 409datathrough: a post 422{ code: 'VALIDATION', fieldErrors, formError }, a slug 409 and a slot 422 reach the admin form as in local mode. The forwarded blog facade (server/utils/admin-blog-forward.ts) turns them back into the layer’s results, soadminPostWriteErroranswers as before; a web 404 is the same 404. - Previews. Forwarded slot views get their same-origin
/m/…URLs (src,poster, eachsrcsetentry) prefixed withMEDIA_API_URL, as forwarded asset URLs are. - Slot routes. All four need the admin token, answer
Cache-Control: no-store, and map a local library error (mediaErrorToHttp, e.g. frozen writes) to its status.
Tests: core/admin/tests/admin-blog-forward.spec.ts, core/admin/tests/admin-slots-routes.spec.ts, and the forwardToWeb case in core/admin/tests/media-service.spec.ts.
Public site still exposes POST /api/messages (contact form). Listing/deleting messages is admin-only.
See also API UML and messages API.
Write errors
A failed POST /api/admin/posts or PUT /api/admin/posts/:id answers with { fieldErrors, formError } in the data of Nitro’s JSON error body (adminPostWriteError in packages/web-layer-admin/server/utils/validation-error.ts). The form reads it with readServerFormError (UI components § Forms).
| Status | When | data |
|---|---|---|
422 |
The body fails the shared schema | { fieldErrors, formError }, one message list per field |
409 |
The slug belongs to another post | { fieldErrors: { slug: [message] } } (owner Q5 A) |
404 |
The post doesn’t exist (update) | { formError: message } |
400 |
Any other rejected write | { formError: message } |
Every invalid body gets a 422 with a message per field. This replaced a 400 that carried only the first problem, as its status message, so clients that read the old texts (such as Invalid body: title, slug, and body are required non-empty strings) must read data instead. The body is parsed by core/web/server/api/posts/parse-body.ts on the shared schema (packages/web-layer-admin/shared/blog-schema.ts, owner Q1 A). The messages:
title: “Enter a title.” (missing, not text, or blank after trimming);slug: “Enter a slug.” (missing, not text, or blank), or “Use lowercase letters, numbers and hyphens in the slug.” (nothing valid left after normalising, such as!!!);excerpt: “The excerpt must be text.”;body: “Enter the post body.”;status: “Choose Draft or Published.”;- form level: “Send the post as a JSON object.” (the body isn’t an object) and, on update, “Change at least one field.” (no known field set; unknown keys are dropped).
The status message is the form-level message, else the first field message. The messages are ASCII because h3 strips other characters from status messages; a test enforces it. A 422 body, abridged (Nitro also sends error, url and message):
{
"statusCode": 422,
"statusMessage": "Enter a title.",
"data": {
"fieldErrors": {
"title": ["Enter a title."],
"body": ["Enter the post body."]
}
}
}
Web write endpoints
The public web owns posts, slots and the usage list, so it serves the authenticated post, slot and rebuild routes the admin forwards to in production (plan 4). Each needs the admin principal (requireMediaPrincipal(event, 'admin'), the same auth as /api/media/*): no token or a wrong one is 401 Unauthorized, and a tenant token (tgmc_mt_…) is 403 admin_only, before anything is read. Tenant tokens are not enabled yet (verifyMediaTenantToken accepts none), so today a tenant token is also a 401; the 403 applies once they are. Every answer, errors included, is Cache-Control: no-store. The code is core/web/server/api/blog/posts/ with core/web/server/utils/blog-post-writes.ts.
| Method | Path | Answer |
|---|---|---|
GET |
/api/blog/posts |
Every post, drafts too, each with needsMedia: boolean |
POST |
/api/blog/posts |
The created BlogPost; records its media usage |
GET |
/api/blog/posts/:id |
The BlogPost (drafts too); 404 Post not found |
PUT |
/api/blog/posts/:id |
The updated BlogPost; updates its media usage; 404 Post not found |
DELETE |
/api/blog/posts/:id |
{ ok: true }; clears its media usage; 404 Post not found |
GET |
/api/media-slots/records |
{ slots: Array<{ record, view, needsMedia, seed }> } |
PUT |
/api/media-slots/:id |
The saved slot record; updates its media usage; 422 field errors; 404 Media slot not found |
POST |
/api/media-slots/:id/reset |
The slot reset to its JSON seed; 404 when it has no seed |
POST |
/api/media-usage/rebuild |
RebuildUsageResult ({ added, removed, countersRepaired }); 503 without a library |
- Errors. The write errors shapes, with a
codeindata: 422{ code: 'VALIDATION', fieldErrors, formError? }, 409{ code: 'SLUG_CONFLICT', fieldErrors: { slug: [message] } }, 404{ formError }. - Usage. Each write builds its own usage sync (
createMediaUsageSync, one per write) on the web’s media library, withdeferset toevent.waitUntil:pendingrows before the store write,liverows after it in the background (Usage list writes). A library that cannot open does not fail the write: the post is saved without usage rows and the server logsmedia.usage_library_unavailablewith the error’s name only; the rebuild repairs the list. - Covers. A create or update whose
coverAssetIdnames an asset of another tenant is a 422 oncoverAssetId(“Pick an image from the portfolio library”); a missing asset still saves (site media § Blog covers and embeds). -
needsMedia(postsNeedingMedia,core/web/server/utils/post-media-status.ts). A published post needs media when itscoverAssetIddoes not resolve (or resolves to a kind a cover cannot show), when a block body reference does not resolve, or when it has nocoverAssetIdand its cover falls to the placeholder. Drafts are never flagged. The whole list resolves in oneresolveMediaRefscall; the slots are read only when a published post has no cover id, and their views may make a second (cached) resolve call for the slots’ own assets. - Slots and the rebuild. The slot routes and the rebuild share the auth and
no-store(requireAdminWriteinblog-post-writes.ts). Their fields, validation and Reset to seed are in site media § Media slots and placeholders, and the rebuild in Usage list writes. A slot 422 carries{ code: 'VALIDATION', fieldErrors }with one message per field, in the arrayuseForm()reads.
Tests: core/web/tests/server/api/blog-posts-routes.spec.ts (its auth table covers all nine route files), core/web/tests/server/api/media-slots-admin-routes.spec.ts, core/web/tests/server/utils/media-slot-write.spec.ts, core/web/tests/server/utils/post-media-status.spec.ts.
Local media library (DAM)
/admin/media is separate from MinIO CDN. The page uses @tgmc/media-client against /api/admin/media/*. By default the admin server uses @tgmc/media with SQLite + filesystem under MEDIA_LOCAL_ROOT (Compose: /app/data/admin-media on the ./data volume).
Layout: drop zone (drag-and-drop or browse; images, SVG, audio, video, 3D / XR, documents; an unsupported type is named in the error line and not staged) → upload form (app/components/AdminMediaUploadForm.vue: dropped files wait here, nothing uploads yet; one fieldset per file, its legend the filename and kind, with Title (required, 3–80 characters) and, for images and SVG, Alt text (required, at most 150) or Decorative (no alt text); video gets optional alt text, other kinds none; Remove per file, Upload and Cancel. Focus moves to the first new file’s Title. Upload checks every file first, marks the empty fields and focuses the first; then files upload one at a time with “Uploading N of M · name” in a role="status" line, each new asset prepended as it lands — no Refresh button — and leaving the form; after the last one focus moves to the first new tile. A server invalid_meta stops the run and shows the issues on that file’s fields; a 415 names the refused file) → Kind segmented control with counts (image / svg / audio / video / model / document, client-side over the loaded assets; a note appears while more can be loaded) → Tag filter chips when any asset has meta.tags → thumbnail grid (app/components/AdminMediaTile.vue: the previewUrl image for images and SVG, otherwise the kind’s Lucide icon and MIME type — app/utils/media-kind.ts; filename, kind icon and label, size, tags; a broken preview falls back to the icon) → Load more below the grid (next 100-asset API page, appended without duplicates — repeated rows count toward the next offset, so a page of rows already loaded still moves paging on; a role="status" line says how many were added and when all are shown; when the last page has loaded the button goes away and focus moves to the first new tile, or the page heading; it is disabled only while a delete request is in flight: a hidden row stays in the loaded list until its DELETE lands, so the next offset stays right while an Undo is pending) → detail drawer (app/components/AdminMediaDrawer.vue; a sticky side panel ≥1080 px, capped at the viewport height and scrolling inside so its controls stay reachable; below that a modal full-screen sheet that also shows the page’s error / Undo / status line, app/components/AdminMediaMessages.vue) with the preview by kind (image, <audio> / <video> with preload="metadata", or a facts panel for 3D and documents), type, size, Public URL (wraps; Copy URL and Open in a new tab), storage path (m/pf/i/<name>.<ext>, wraps instead of scrolling) + short id + Copy (both copies report in a role="status" line, including a failed copy), Details (app/components/AdminMediaMetaForm.vue: Title, Alt text or Decorative — by kind, as in the upload form — Description, Credit (blank uses the default, Tamara Mack); Save details sends every field through PATCH …/assets/:id, the server decides and its invalid_meta issues land on the fields; each field has its hint and error tied in with aria-describedby and aria-invalid while it has an error; the first invalid field takes focus; a role="status" line says “Details saved.” or what to fix; “Unsaved changes” shows while the form differs from the stored meta, Reset restores it, and leaving the page, closing the drawer (Close or Esc) or opening another asset then asks first (app/composables/useUnsavedDetails.ts); the fields are shared with the upload form in AdminMediaMetaFields.vue and checked by app/utils/media-meta-form.ts), File name (app/components/AdminMediaRename.vue: the stored filename and Rename…, which opens an inline form with focus in the name field and the warning that the public URL changes and links to the old /m/ URL stop working, with no redirects; the extension must stay; a taken name shows the free one with a **Use
Delete UX: the page lists, pages and deletes through the kit’s useCrudResource (UI components § Lists and deletes). Delete… in the drawer (for an unused asset) becomes the kit’s UiConfirmInline, “Delete NAME and its variants?” with Delete and Cancel (Cancel focused; Escape cancels the question and keeps the drawer open) → Delete hides the tile at once and closes the drawer, announces “Deleted NAME.” and shows a UiUndoNotice line with Undo for 8 s (the time stops while the line is hovered or focused) → the cascade DELETE runs when the time ends, or when the page is left. Several deletes can be pending at once, each with its own Undo line beside the page’s message line, so an error message no longer hides an Undo. In the phone sheet the Undo lines sit under its heading with UiUndoNotice’s hold-space: when the 8 s end, a line’s space stays (hidden) until the sheet closes, so the sheet’s content does not jump up (measured at 375 px: 79 px before, 0 after). Undo restores the tile, reopens the drawer if it was open and makes no API call. A failed DELETE restores the tile (and the drawer) and shows “Delete failed.” in the message line, a UiMessage that is its own live region (role="alert" with PrimeVue), so it is spoken once. Since plan 4, Delete… first checks where the asset is used, and an asset in use is refused before the question (Used by, refusal and Delete anyway). The kind filter is client-side and is not in the URL.
Keyboard and focus: opening an asset focuses the drawer heading; Esc closes the drawer and returns focus to the tile that opened it — or the selected asset’s tile when there is no opener, as after Undo or a failed delete restores the drawer; the page heading if that tile is gone (drawerReturnTarget) — except while focus is on a control that uses Esc itself (a select, combobox / listbox, the expanded popup trigger it is on, an input with suggestions, IME composition — app/utils/media-drawer.ts); Tab / Shift+Tab wrap inside the drawer while focus is in it (useFocusTrap from @tgmc/nuxt-layer-base). As a sheet (below 1080 px, useMatchMedia from the base layer) the drawer is aria-modal="true", the rest of the page is inert (useInertOutside, default keep list) and does not scroll; both are restored when it closes. Live regions stay live behind the sheet: [aria-live], role="status" / "alert", the UiAnnouncer, toasts, #teleports and the route announcer are not made inert, so announcements still reach screen readers (WCAG 4.1.3). Those nodes must hold no controls, because they stay reachable. A slower detail response for an earlier click never replaces the asset picked last. Delete… moves focus to Cancel (not Delete), and Cancel or Escape returns it to Delete…. After a delete, focus moves to the new Undo line’s button. Undo returns focus to the restored tile, or to the drawer heading when the drawer reopens or the phone sheet is open (the grid behind the sheet is inert); when the 8 s end with focus on Undo, focus goes to the drawer heading while another asset’s phone sheet is open (messagesInDrawer, the grid behind it is inert), otherwise to the next tile in the grid, else the previous one, else the page heading (owner Q5 A; focusAfter and tileBeside in app/pages/admin/media/index.vue). In the rename form Esc cancels the rename only (the drawer stays open). Every new control is at least 44 px tall and the forms stack in one column on phones.
Set MEDIA_API_URL to forward list/upload/edit/rename/materialize/jobs/process to the portfolio web /api/media/* API (Bearer MEDIA_API_TOKEN or ADMIN_TOKEN). Upload remote uses the web presign → PUT → complete flow from the admin server. Upstream errors (upstreamError in server/utils/media-service.ts): a web API 401 or 403 (other than a 403 admin_only, passed through with its data) means it rejected the admin server’s token (MEDIA_API_TOKEN / ADMIN_TOKEN), not the signed-in user’s, so the admin answers 502 “Media API rejected the admin server’s token” and the media page shows it instead of signing the user out (a passed-through 401 used to sign out in a loop). A web 5xx, and any failed presigned PUT to S3 / MinIO, is a 502 with a generic message; another 4xx keeps its status and the web’s own statusMessage (the 400 invalid_meta, 409 name_conflict / in_use and 415 bodies keep their data). The raw upstream body is logged on the admin server (media_api.upstream_error / media_api.upload_put_failed, first 2000 characters) and never sent to the browser. Every web API call is cut off after MEDIA_API_TIMEOUT_MS (60 s); the presigned PUT, complete and ingest/svg (which sanitize the whole upload on the web) after MEDIA_API_UPLOAD_TIMEOUT_MS (10 min), answered 504 “… timed out”, so a stalled web API never hangs the admin.
Upload size caps. POST /api/admin/media/assets (base64 JSON, local and forward mode) caps the decoded file per kind with the presign caps (uploadCapBytes, MEDIA_MAX_UPLOAD_BYTES_<KIND>; media-nuxt § Upload size cap) and SVG at the web’s 4 MiB ingest/svg limit (server/utils/media-upload-caps.ts): over it is a 413 data: { code: 'too_large', maxBytes } before anything is stored, and before the body is read a declared Content-Length is checked: against the kind the page names in the query (POST …/assets?kind=image, sent by @tgmc/media-client uploadBase64; 413 too_large with that kind’s maxBytes), and in any case against the largest cap as base64; a chunked body without Content-Length is a 411. The media page reads the same caps from GET /api/admin/media/limits once and refuses a staged file over its kind’s cap before it reads and encodes it (“huge.png is 30.0 MB; image uploads are limited to 25.0 MB.”, app/utils/media-upload-limits.ts); the rest stays staged. Moving local mode to the presign → PUT flow (no base64, no whole file in memory) is in the TODO.
Upload sanitizing. Every admin upload is cleaned before it is stored (media § Upload sanitizing): rasters lose their metadata (EXIF, GPS, XMP, C2PA), SVG loses editor metadata, scripts, event handlers and external references, a PDF’s document info is replaced by its title (XMP removed) and its scripts, actions, attachments and forms are stripped, and MP4 is remuxed without metadata (image § Sanitize). The admin server runs the full sanitizer (server/utils/media-sanitize.ts, createFullUploadSanitizer from @tgmc/image/sanitize): in local mode inside the library’s ingest; in forward mode on the admin server first. A sanitized SVG is then sent in the request body (POST /api/media/ingest/svg, which runs svgo on it again and scans the result before storing); a PDF or MP4 goes through the presigned PUT with preSanitized: true, so the web API (which sanitizes only rasters and SVG) accepts it. MP4 needs ffmpeg: FFMPEG_PATH, else ffmpeg on PATH (docker/Dockerfile.admin installs it), else the optional ffmpeg-static; without one an MP4 upload is a 503 naming the missing tool. svgo and pdf-lib are admin dependencies and ship in the admin .output. A type outside the media kinds (HTML, unknown extensions, HEIC) is a 415 unsupported_type, refused before anything is uploaded; a file that is damaged or not what its name says is a 415 invalid_upload. In forward mode a web API 415 reaches the page as the same 415, with the server’s message and its data (code plus format or mime), as 400 invalid_meta and 409 name_conflict already do.
Previews and URLs. Every asset from the list, detail and upload routes carries publicUrl (the original) and previewUrl (the t thumbnail for images when it is ready, the original for SVG / audio / video, null for 3D and documents; media-nuxt § Asset URLs). Both are versioned with the object’s content hash (?v=<sha8>, media § Versioned public URLs), in local mode too, so Copy URL gives a link that changes when the bytes do.
- Usage list (local): the local library keeps its usage list (which published pages use each asset) in the same
media.sqlite, in themedia_usagetable (SqliteUsageStore, media § Usage list and delete safeguards); an existing database gains the table on its next open. Delete refuses an asset listed there unless forced, exactly like the web API. Blog post and slot writes record their media usage on this library (pending before the publish, live after; site media § Usage list writes). In forward mode the web records it: post and slot writes are forwarded (Forward mode). - Local DAM: the admin serves its own blobs on
/m/**(server/routes/m/[...path].ts, the@tgmc/media-nuxtstand-in withRangesupport, so video plays in Safari), and URLs are same-origin (/m/pf/i/<name>.<ext>) unlessMEDIA_PUBLIC_BASE_URLis set. The local library runs the on-ingest recipes (media § On-ingest recipes) synchronously through itsonIngestedhook, so an uploaded image comes back with its meta and itst/640/1280/1920variants; a recipe failure is recorded on the asset (Processing section) and never fails the upload. Re-run processing callsrunOnIngestRecipesdirectly. - Forward (
MEDIA_API_URL): the web API builds the URLs; root-relative ones (web on a filesystem backend) are prefixed withMEDIA_API_URL. The browser must reach that host, so whenMEDIA_API_URLis an internal Compose name (e.g.http://web:4200), setMEDIA_PUBLIC_BASE_URLon the web app to a host the browser can open.
Used by, refusal and Delete anyway
Plan 4 (planner’s calls 11 and 12). The flow lives in app/composables/useMediaDeleteFlow.ts; the list is app/components/AdminMediaUsedBy.vue (props { pages, loading, error }, pages: null = not loaded yet).
- Used by. Opening an asset reads
GET /api/admin/media/assets/:id/usage. The drawer’s Used by section (after the facts) lists each page’s label linked to that page on the public site (new tab, “(opens in a new tab)” for screen readers), with a “pending” tag for a page whose publish is still being recorded. No pages reads “Not used on any published page.”; a failed read says “Unable to check where this asset is used. Reopen the asset to try again.” Usage rows store site paths (/blog/…,/work), which would open on the admin’s own origin, sousageHref(app/utils/media-usage-links.ts) resolves them onruntimeConfig.public.siteUrl(NUXT_PUBLIC_SITE_URL, elseSITE_URLat build), else onruntimeConfig.public.mediaApiOrigin. A row links only when it resolves on that base origin: a path the URL parser reads as another host (//evil.test,/\evil.test, a tab or newline after the slash) and an absolute URL off the site show as text.mediaApiOriginis set per request byserver/plugins/media-site-origin.tsfrom the runtime env (NUXT_MEDIA_API_URL, elseMEDIA_API_URL, the server’s own order): only its http(s) origin, never userinfo, path or query, and nothing at all when a site URL is set. SetNUXT_PUBLIC_SITE_URLso no API origin (possibly an internal host) reaches the browser. With neither (a local-only admin), each page shows as its label and its path in<code>: no link that would 404. The same component lists the pages in the refusal and the rename warning. - Delete… checks first. The button reads the usage again: its label becomes “Checking…” (
aria-disabled, so focus stays on it; a second press does nothing) and “Checking…” is announced.- Not in use: the confirm in place and the 8 s Undo above, unchanged.
- In use: the refusal replaces the button. The message line says “Not deleted: used by 2 published pages: Harbor notes, About.” (
inUseRefusalMessage, also used bydeleteRefusedMessage), announced once more throughannounce()because the line is inserted with its text. The drawer shows “Not deleted: used by 2 published pages” (focused), the pages, and a separate Delete anyway…. - A failed check says “Unable to check where this asset is used. Try again.” and keeps Delete…; a 401 signs out.
- Delete anyway… asks in place with
UiConfirmInline: “Delete anyway? The 2 pages will show a placeholder.” (Cancel focused; Cancel orEschands focus back to Delete anyway…). Delete starts the same 8 s Undo (“Deleted NAME.”, focus on Undo); its commit callsdeleteAsset(id, { force: true })(DELETE …?force=1). Undo keeps the asset (“Restored NAME.”, focus on the drawer heading), and the next Delete… starts from the check again, not forced. Delete anyway is only offered from a refusal, so a forced delete always names pages. - A 409 at commit (a page published during the Undo of an unforced delete): the asset is restored and the refusal shows again with the pages from the 409, which also replace the Used by list. A 409 that names no page shows only the message line (“Not deleted: used by published pages.”, announced) and keeps Delete…: Delete anyway is never offered without pages. Focus moves to the refusal when nothing holds focus, focus is in the drawer, or the drawer is the phone sheet; otherwise the message line and the announcement tell the reader.
- Rename warning. When the drawer’s Used by list is not empty, the rename form adds “Used by 2 published pages; their links update automatically.” (singular: “Used by 1 published page; its link updates automatically.”) with the pages, and describes the name field by it. Its note then reads “Links on these pages update automatically; outside links to the old /m/ URL stop working (no redirects).”, not the generic “update any page that uses it”.
- Rename checks first. Submitting reads the usage again (
checkUsageinuseMediaDeleteFlow, which also refreshes the drawer’s Used by list): “Checking…” in the form’s status line, Rename busy (aria-busy, focus stays). With pages it shows the warning and asks once in place, “Rename OLD to NEW?” (Rename / Cancel; Cancel returns focus to the name field). A failed read shows “Unable to check where this asset is used.” and asks the same confirm; a 401 signs out. With no pages it renames at once. So a list that was stale, still loading or failed when the drawer opened never skips the confirm. - Confirming returns focus to the form’s Rename button (a template ref), which stays focusable while the request runs (
UiButtonloadingisaria-busy, neverdisabled).
- Rename checks first. Submitting reads the usage again (
- Rebuild usage list (
AdminMediaUsageRebuild.vue, under the page lead; the page runs the request):POST /api/admin/media/usage/rebuildrecomputes which published pages use which assets, the same rebuild as the post-deploy step (CI/CD) and its recovery. While it runs the label is “Rebuilding…” (aria-disabled, focus stays). The result shows under the button and is announced: “Usage list rebuilt: 3 added, 1 removed.” A 503 says “Usage list not rebuilt: the media library is unavailable. Try again later.”; other failures “Usage list not rebuilt. Try again.”; a 401 signs out. An open drawer re-reads its Used by list after a rebuild.
Tests: core/admin/tests/admin-media-used-by.spec.ts mounts the page (the kit’s real confirm-undo, UiConfirmInline and UiUndoNotice). Its last block is the plan-4 e2e flow driven by the keyboard alone (Tab, Shift+Tab, Enter, typing): delete an asset used by a published post, the refusal, Delete anyway, Undo, and the asset kept; then the rename warning and its one confirm. It stands in for a Cypress spec because scripts/e2e-regression.mjs builds and serves core/web only, so the admin app isn’t reachable in e2e.
Media picker
app/components/AdminMediaPicker.vue chooses a library asset for another form (for the slot editor, the blog cover and Insert media). Props { open, kinds, title }; it emits select(asset) (the list row, a MediaAsset with previewUrl) and then close(), and close() alone on Escape, Cancel or the backdrop. The parent owns open. Clear sits beside the field that opens the picker, not in the dialog.
- Data. On open it lists each allowed kind with
GET /api/admin/media/assets?tenant=portfolio&kind=<kind>&limit=100&offset=…(the site rendersportfolioassets only, so other tenants’ assets are never offered) (the route takes one kind, so one request per kind, in parallel), newest first within each batch. Load more fetches the next page of every kind that returned a full page; the next offsets count from the offsets sent. One watcher coversopenandkinds, so setting both in the same tick loads once. A response is applied only if it belongs to the current open and load (every open, close and reload starts a new one), so a slow response for earlier kinds never adds their rows. - Layout. A
UiDialogtitled bytitle, at most 56 rem wide and 2 rem inside the viewport, so there is no page overflow at 320 px. Filter by name (a labelled search field, client-side over the loaded rows: name, file name and title) → a grid ofAdminMediaTiletiles (preview, name, kind, size) with the alt text under each (“Alt: …”, “Decorative (no alt text)” or “No alt text”) → Load more. Withoutselectedthe tile has noaria-pressed, so it reads as a plain button. - States, in one live region. The dialog’s
role="status"line carries every state, so screen readers hear each: “Loading…”, “3 assets loaded.”, “Loading more…” and then the Load more result, “No images or SVGs in the library yet.” (with Go to Media,/admin/media; the kinds come frommediaKindsPhraseinapp/utils/media-kind.ts, every kind reads “media”), and a failure: “Unable to load the media library.” or “Unable to load more assets.” with Retry. The grid filters on every keystroke, but the line reports the filter only after 500 ms without typing (“2 of 3 assets match.” or “No images or SVGs match your filter.”, never the typed text), so one filter change is one announcement. A 401 for the token still signed in reads “Your session has expired. Sign in again.” with Sign in again instead of Retry: it signs out and goes to the sign-in page withexpired=1and a redirect back (expiredSignInTarget). It is a button, not an automatic sign-out as on the media page, because the form behind the picker may hold unsaved edits. - Keyboard and focus. Opening moves focus to the filter: it has
autofocus, which PrimeVue’s dialog honours (it would otherwise focus its close button), and the native<dialog>mode focuses it after render. Tiles are native buttons in Tab order, as on the media page: Enter or Space chooses one. After the last page loads, the button goes and focus moves to the first new tile. On close, focus returns to the element that had it when the picker opened. Every control is at least 44 px (--touch-target); nothing depends on hover.
Tests: core/admin/tests/admin-media-picker.spec.ts.
Slots
/admin/slots (app/pages/admin/slots.vue, helpers in app/utils/media-slots.ts; nav label Slots, after Media) edits the site’s media slots (site media § Media slots and placeholders) through GET /api/admin/media/slots, PUT /api/admin/media/slots/:id and POST /api/admin/media/slots/:id/reset, so it follows the database selector in local mode and the web in forward mode.
- List. One card per slot: a preview (the view’s image, else the kind’s icon with “Placeholder”, “Unavailable” or the kind; hidden from assistive tech, since Source says the same;
slotPreviewSrc). A static slot’s root-relativesrcis a site path the admin does not serve, so it resolves onNUXT_PUBLIC_SITE_URLwhen set, else the card shows the icon. In forward mode the views arrive absolutized on the fullMEDIA_API_URLbase (a server-side prefix, like an asset’spreviewUrl; Nodefetchrefuses userinfo URLs, so in practice it is that origin), unlike Used by links, which use the site URL or only the API’s origin; captions URLs stay root-relative (the admin does not render them), then Id, Kind, Ratio, Source and Alt. Source follows the slot’s precedence:Library: <asset file name>(the id until the name loads,(unavailable)when the asset no longer resolves),Static: <src>, orPlaceholder. A slot whose view is a placeholder or unavailable also reads Needs media (icon and text, not colour alone). Cards stack on a phone and put the preview beside the facts from the tablet breakpoint; long ids and paths wrap. -
Filter. **All Needs media** is a button group with aria-pressed, kept in the URL as?filter=needs-media(useRouteQueryStatewithslotListCodec). The slot being edited stays listed under Needs media after its save fills it. - Editor. Edit (named “Edit
") opens the form in place inside the card, one slot at a time, with no modal; focus moves to **Choose from library**. It is the forms template (`useForm`, `UiForm`, `UiFormErrorSummary`, `UiFormField`, `UiFormActions`; ids `#slot- `): - Library asset: a group named by the field label (
role="group", the error summary’s link focuses it) holding the current asset’s name, Choose from library (which carries the field’saria-invalidand error description) (AdminMediaPickerover the kinds the slot accepts,SLOT_ACCEPTED_KINDS: image or SVG for image and SVG slots, video for video slots; titled “Choose an image”, “Choose an SVG” or “Choose a video”) and Clear (removes the asset, keeps the static path; focus returns to Choose). Both announce “… Save to apply it.”. - Static path, Decorative, Alt text (required unless decorative) and Caption. Checking Decorative disables the alt field but keeps its text until you save (its hint says so), so unchecking brings it back; the save sends
alt: ''while decorative, which clears it. Each change is announced (“Alt text not used: the slot is decorative.” / “Alt text is used again.”). Opening a decorative slot with a stored alt leaves the form clean. The checkbox sits in a 44 px label box (touch-target), so the whole box toggles it. - Video slots only: a Captions (WebVTT) group with Captions file, Language and Track label; all three empty sends
captions: null. - Save sends
{ assetId, src, alt, decorative, caption, captions }(empty text asnull). The form has no client rules: the route validates, and its 422fieldErrorsland on the fields and in the summary (captions.srcand so on included); a body error reported underformshows as the summary’s message. “Slot saved.” is shown and announced, and the list reloads (needsMedia, Source). A 401 signs out with no message. - Reset to seed… (slots with a JSON seed) confirms in place with
UiConfirmInline(“Resetto its seed? Its saved values are replaced.", Reset / Cancel; Cancel or Escape returns focus). It then calls the reset route, reloads the form and the list, and says " is back to its seed." in the editor's message line; a 404 reads " has no seed to reset to.". Both are also announced, since the message line is inserted with its text. - Unsaved changes. Opening another slot or Close with unsaved edits asks in place (“Discard unsaved changes to
?", Discard / Cancel). Leaving the page opens the "Leave without saving?" dialog (`useUnsavedChangesGuard`). Switching the database closes the editor and reloads the list. - Focus on close. Focus returns to the slot’s Edit. A slot that left the list (saved out of Needs media) hands it to the next listed slot’s Edit, else to the pressed filter button.
- Library asset: a group named by the field label (
Tests: core/admin/tests/admin-slots-page.spec.ts (mounted with the real form kit), core/admin/tests/admin-nav.spec.ts.
Follow-ups: kind-appropriate presets, richer previews (3D poster, document excerpt, waveform) and the remaining drawer items — see interaction-redesign.md#todo.
Plan: docs/plans/2026-09-22-003-feat-admin-media-ui-plan.md.
Local CDN (MinIO)
MinIO runs in every admin stack. After syncing public assets:
NUXT_APP_CDN_URL=http://127.0.0.1:4410/portfolio-assets
Restart the public web/lambda service after changing NUXT_APP_CDN_URL. Details: cdn-guide.md.
Sync workflow
- Build the public app for the target environment (
npm run buildwith the rightSYS_ENV, or letdocker:admin --buildstage outputs). - In admin → CDN, select the matching database (maps to
.outputdir above). - Click Sync from .output.
- The page shows completed and total files. If the request fails or the admin restarts, click Sync from .output again to retry the unfinished files. A changed staged output starts a fresh operation.
The admin records one JSON manifest per selected output environment under data/admin-cdn-sync (the Docker /app/data volume). Set NUXT_CDN_SYNC_STATE_DIR to another writable persistent directory if needed. Each successful PUT is checkpointed; changing the normalized MinIO endpoint or bucket starts a new operation, including for older manifests without endpoint identity. Repeating a completed POST returns its result without another PUT; clicking Sync again sends an explicit restart. Progress state contains paths and file status, not MinIO credentials. This recovery assumes one admin process; concurrent replicas and writes to the same destination key need a separate ownership design.
Code walkthrough
Database selection is explicit in code — not tied to SYS_ENV on the admin container.
Client (packages/web-layer-admin/app/utils/admin-fetch.ts, provided by plugins/admin-session.client.ts):
// Same-origin requests only: Bearer token + X-Admin-Database from the in-memory session.
const { token, database } = getSession();
if (token) headers.set('Authorization', `Bearer ${token}`);
headers.set(ADMIN_DATABASE_HEADER, database);
// In a page:
const adminFetch = useAdminFetch();
await adminFetch('/api/admin/posts');
Server resolve (core/admin/server/utils/admin-database.ts):
// Precedence: ?db= → X-Admin-Database → DEFAULT_ADMIN_DATABASE
const selected = parseAdminDatabase(fromQuery) ?? parseAdminDatabase(fromHeader) ?? defaultAdminDatabase(config);
// The UI id is the store's explicit dataBackend (overrides DATA_BACKEND and the SYS_ENV default)
createMessageStore(messageStoreOptionsForDatabase(config, selected));
Blog plugin (core/admin/server/plugins/admin-blog.ts) registers, once at startup, how the blog API is built for a request; requireAdminBlog (@tgmc/web-layer-admin/server/utils/admin-handler) runs it only after the token check, so no other request (pages, /_nuxt, /m/**) resolves a database, and a ?db= that is not allowed is a 400 only on the blog route that reads it (it used to fail every page). POST / PUT /api/admin/posts also check the token before they read the body.
The global request hook selects a store cached per backend and attaches a per-request facade. It runs before route authentication; it does not create a fresh pool per request.
// Per-request store (public app uses a singleton instead), resolved lazily after auth.
registerAdminBlogResolver((event) => {
const database = resolveAdminDatabase(event, config);
const store = createBlogPostStoreForDatabase(config, database);
return {/* listAllPosts, … */};
});
CDN sync maps the selected database to a staged .output folder:
// sqlite → .output/local/public, postgres → .output/development/public, etc.
syncPublicAssetsToMinio(config, outputSysEnvForDatabase(database));
Development notes
- Do not add
extends: ['@tgmc/web-layer-admin']back tocore/web/nuxt.config.ts. - Admin reuses
core/webUi*components and#web-serverstore factories; keep imports on the documented entry boundaries (utilities). core/adminnpm run devis for layer work only — you must supply DB URLs and tokens locally; preferdocker:adminfor integration testing.- Tests:
cd core/admin && npm test(Vitest foradmin-database, MinIO helpers, media-service, the/m/**route, media presets, the media UI utils (focus trap, kind icons, paging), the media page’s drop zone / tiles / drawer / Load more / delete-undo contract, the upload form, Details editor and rename control (mounted with@vue/test-utilsin jsdom: labels,aria-describedby/aria-invalid, live regions, focus moves,Esc), the blog editor’s and list’s delete flow (blog-edit-ui.spec.ts,blog-list-ui.spec.ts: confirm in place, the handoff, Undo, the status filter in the URL), upload sanitizing, and the Nitroexternals.inlinelist, and thatdocker-compose.admin.ymlsets aNUXT_*name for every adminruntimeConfigkey). nitro.externals.inlinemust keepnuxtand@primeuix/utils(Nuxt 4.6 renderer; note)..output/adminis built on the host, so container env only reachesruntimeConfigthroughNUXT_<KEY>/NUXT_PUBLIC_<KEY>names. When you add aruntimeConfigkey, add itsNUXT_*entry to the admin service indocker/docker-compose.admin.yml; when it has a plain twin, write it as${NUXT_X:-<the twin's value>}so a host override wins (both guarded bycore/admin/tests/docker-runtime-env.spec.ts).
Troubleshooting
| Symptom | Check |
|---|---|
401 on all admin APIs |
ADMIN_TOKEN in .env.admin; token pasted at /admin |
| “That token is not valid for this environment.” | The token doesn’t match this stack’s ADMIN_TOKEN (.env.admin); nothing was saved |
| “Admin writes are disabled (ADMIN_TOKEN not configured)” | The server has no ADMIN_TOKEN: set it (or NUXT_ADMIN_TOKEN) in .env.admin, then docker:admin again |
| “The admin server failed (5xx …)” | The session check crashed: read docker compose -f docker/docker-compose.admin.yml logs admin |
“Session expired” on /admin |
The server rejected the saved token; enter the current ADMIN_TOKEN again |
| “ADMIN_TOKEN is a placeholder or shorter than 32 characters” | Set a strong ADMIN_TOKEN in .env.admin (openssl rand -hex 32), then docker:admin again |
403 “Host not allowed” |
Open the admin at http://127.0.0.1:4400 or http://localhost:4400, or add the name to ADMIN_ALLOWED_HOSTS in .env.admin |
| “Media API rejected the admin server’s token” (502) | Forward mode: the web API refused MEDIA_API_TOKEN (or ADMIN_TOKEN) in .env.admin; set it to the target’s admin token. The admin logs media_api.upstream_error |
| Signed out in a new tab | Expected — the session lives in sessionStorage and belongs to one tab |
| Empty messages/posts after switch | Expected — each database is isolated; seed or create data per backend |
| CDN sync skipped / 0 files | Build missing for that DB’s .output/<sysEnv>/public; run docker:admin --build |
| Postgres connection errors | tgmc-postgres-admin healthy; ADMIN_POSTGRES_DATABASE_URL uses host postgres inside Compose |
| DynamoDB errors | dynamodb-init completed; tables portfolio-admin-Messages / portfolio-admin-Posts |
| Port already in use | Change ADMIN_PORT, POSTGRES_PORT, or DYNAMODB_PORT in .env.admin |
| 500 “Either manifest or precomputed data must be provided” | Stale .output/admin from before the Nuxt 4.6 fix: npm run build:admin, then docker:admin (note) |
404 “Page not found: /” at http://127.0.0.1:4400/ |
Stale .output/admin from before the / → /admin redirect (routeRules in core/admin/nuxt.config.ts): npm run build:admin, then docker:admin |
CDN 500 “MinIO is not configured” |
The admin service is missing NUXT_S3_* env; recreate with the current docker/docker-compose.admin.yml (docker:admin) |
See also
- docker.md — all Compose stacks
- docker/README.md — port map + admin stack section
- data-stores.md — SQLite / Postgres / Dynamo adapters
- cdn-guide.md — production CDN vs local MinIO