Skip to the content.

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

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).

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).

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.

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

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.

Token strength and Host check

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.

Guarded pages and redirects

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

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:

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

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 ** button; Esc or Cancel closes it and returns focus to Rename…, as does a successful rename, announced in a `role="status"` line; the tile, preview and Public URL switch to the new key; `POST …/assets/:id/rename`), **Tags** add/remove (`PATCH …/assets/:id`), **Processing** (`app/components/AdminMediaProcessing.vue`: one row per on-ingest step — Thumbnail · 320 px, 640 / 1280 / 1920 px — with Queued / Running / Ready / Failed / Not started / Stalled and the error (the last two mean a step waited past the server's 15-minute deadline; a hint and the live region point to Re-run), `meta.processingError` when the original could not be decoded, and **Re-run processing** (`POST …/assets/:id/process`; idempotent — ready variants are kept, failed and missing ones are made again, meta is refreshed; while it is in flight the button reads “Re-running…” and is `aria-disabled`, not `disabled`, so keyboard focus stays on it). While steps are queued or running the page re-reads the detail every 3 s (at most 40 times, plus a few polls after a queued re-run; `app/utils/media-processing-poll.ts`) and stops when the drawer closes, another asset is picked, the asset is deleted or the page unmounts (a late detail response is then dropped). A failed poll stops polling and shows “Unable to refresh the processing status.”; a poll never clears a page error. A `role="status"` line announces when processing finishes or fails), variants (role, catalog code and key path) with status words (✓ Ready / ◷ Processing / ✕ Failed), and **Make a variant** presets (`app/utils/media-presets.ts`: Card = catalog `640` webp, Hero = catalog `1920` avif — both replace their object in place when made again — and Square 800×800 as a custom recipe with a fresh `@c-…` key each time; image-only for now). Uploading a filename that is already taken shows “… is already in the library as . Rename it to -2. and upload again.” (409 `name_conflict`; names are unique per kind whatever the extension, so `hero.jpg` conflicts with `hero.png`). A filename whose extension does not match the file type is rejected with the corrected filename. A failed upload or variant shows the server's reason for a client error, e.g. “Materialize failed. Image edge exceeds max (4096px).” for a 422 (`app/utils/media-errors.ts`); a 5xx shows the plain failure text. Create variant failures (and invalid recipe JSON) render inline under **Make a variant** (`p#media-variant-error`, `role="alert"`, referenced by `aria-describedby` from the picker, the recipe textarea and the button), because the page's message line is out of view while the drawer is scrolled to its variants; it clears on the next attempt and when the drawer closes or another asset opens. **Custom recipe (JSON)…** reveals the role + JSON editor only when chosen. Re-making a catalog variant keeps the existing one ready until the new one succeeds. The variant section lives in `app/components/AdminMediaVariants.vue` (the page supplies the delete controls through its slot). Messages name the file, not the id. Editorial facets stay on `meta.tags` / facet keys — not extra kinds (see [`docs/packages/media.md`](/portfolio/packages/media.html)).

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.

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).

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.

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.

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

  1. Build the public app for the target environment (npm run build with the right SYS_ENV, or let docker:admin --build stage outputs).
  2. In admin → CDN, select the matching database (maps to .output dir above).
  3. Click Sync from .output.
  4. 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

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