@tgmc/media-nuxt
Nuxt module that mounts /api/media/* (plus the local /m/** CDN stand-in) and owns MediaLibrary resolution (local SQLite/FS or AWS).
Package README: packages/media-nuxt/README.md.
Usage
// core/web/nuxt.config.ts
modules: [, /* … */ '@tgmc/media-nuxt'];
Handlers live under packages/media-nuxt/runtime/server/ (api/ and routes/, registered through addServerScanDir). Re-exported utils: @tgmc/media-nuxt/runtime/server/utils/media-library, …/media-local-s3, …/media-public-url, …/media-cdn (createLocalMediaCdnHandler, which core/admin mounts on its own /m/**). …/media-asset-events: onMediaAssetChanged(listener) / emitMediaAssetChanged(change), an in-process notice ({ assetId, reason: 'deleted' | 'renamed' | 'meta' | 'processed' }) that the delete, rename, PATCH and process asset routes emit after they succeed; a throwing listener is logged (media.asset_event_listener_failed), never thrown. core/web clears its cached media resolution on it (site-media.md).
Admin /api/admin/media/* is not part of this module.
Auth
Every /api/media/* route except the local _local-s3 PUT authenticates with getScopedMediaLibrary(event, need) (runtime/server/utils/media-auth.ts) and works through the library scoped to the caller (scopeMediaLibrary, see media § Scoped library). The store is opened on first use, so a refusal never touches it. tests/media-route-auth.spec.ts fails if a route calls getMediaLibrary() itself, or builds its own principal or scoped library.
- Principals. The admin token is the
adminprincipal. It resolves as before:NUXT_ADMIN_TOKEN, thenADMIN_TOKEN, thenruntimeConfig.adminToken. A Bearer that starts withtgmc_mt_is a tenant token (tgmc_mt_{tenant code}_{token id}_{secret},media-tenant-tokens.ts) and is never compared with the admin token. Tenant tokens are off until the token map lands (Phase 7 S1-8), so every tenant token is refused for now. An admin token that itself starts withtgmc_mt_would lock the admin out; the server logsadmin_token_tenant_prefixonce (never the token). - 401. A missing Bearer, a wrong one, an unknown tenant token and an unset
ADMIN_TOKENall answer the same 401Unauthorized. So does the admin token itself when it is weak (a placeholder, a value committed to the repo, or under 32 characters;usableAdminTokenfrom@tgmc/web-layer-admin), outside unit tests: a known token on a localhost-bound stack (docker:teston:4300) is reachable through DNS rebinding. - Needs. Each route needs
read,writeoradmin(table below). A tenant on anadminroute is a 403admin_only; a tenant token without the scope is a 403insufficient_scope. - Tenant.
presign,svgand the list readtenantfrom the request: absent → the caller’s own (portfoliofor the admin, so an admin list withouttenantis still Portfolio only); invalid → 400; another tenant from a tenant token → 403tenant_mismatch. The by-id routes andcompleteanswer 404 for another tenant’s asset or key, never 403, so ids don’t leak. - Tenant uploads. A tenant’s presign must send
byteSize(400byte_size_required), itscompleteis always capped (no expand-phase skip), and its SVG always takes the full sanitize path (preSanitized: false). A tenant may only presign the five raster types (png, jpeg, webp, avif, gif) and only send SVG toingest/svg; any other kind or MIME is a 415kind_not_allowedbefore a name is reserved (media § Scoped library). The tenant presign checks run in this order: 400byte_size_required, 415kind_not_allowed, 413too_large. A tenant raster that doesn’t decode is a 415invalid_uploadatcomplete(object deleted, name released), where the admin’s is kept as is.
| Route | Need | Another tenant’s asset or tenant |
|---|---|---|
POST /api/media/ingest/presign |
write |
403 tenant_mismatch |
POST /api/media/ingest/complete |
write |
404 (before any reservation read) |
POST /api/media/ingest/svg |
write |
403 tenant_mismatch |
GET /api/media/assets |
read |
403 tenant_mismatch |
GET /api/media/assets/:id |
read |
404 (its rename is not resumed) |
GET /api/media/assets/:id/usage |
read |
404 |
PATCH /api/media/assets/:id |
write |
404 |
DELETE /api/media/assets/:id |
write |
404; ?force=1 is 403 admin_only |
POST /api/media/assets/:id/rename |
write |
404 |
POST /api/media/assets/:id/process |
admin |
403 admin_only for any tenant |
POST /api/media/assets/:id/materialize |
admin |
403 admin_only for any tenant |
GET /api/media/jobs/:id |
admin |
403 admin_only for any tenant |
Routes
| Route | Behaviour |
|---|---|
POST /api/media/ingest/presign |
{ kind, mime, filename, tenant?, preSanitized?, byteSize? }: normalizes the filename, reserves the key (30 min), returns a presigned PUT signed for exactly byteSize bytes when it is given (echoed back as byteSize; over the kind’s cap → 413 too_large, see Upload size cap). Before anything is reserved (upload sanitizing): any SVG → 415 sanitize_required (send it to POST /api/media/ingest/svg); PDF or MP4 without preSanitized: true → 415 sanitize_required; a mime outside the kinds allowlist → 415 unsupported_type; for a tenant, anything but a raster → 415 kind_not_allowed (see Auth). Taken name (any extension) → 409 with data: { code: 'name_conflict', path, suggestedName, suggestedFilename, suggestedPath }; extension that disagrees with the mime → 400 with the corrected filename. Errors are mapped by mediaErrorToHttp from @tgmc/media |
POST /api/media/ingest/complete |
{ assetId, path, kind, mime, meta, preSanitized?, preSanitizedSig?, byteSize?, … }: an admin PDF or MP4’s preSanitized is checked against preSanitizedSig (Admin preSanitized signature). path must be the key reserved for assetId; a missing/expired reservation is 400, a lost race is 409. When path already belongs to the registered asset assetId, the asset is returned as is (a repeated call never reads, sanitizes or deletes the object). meta must pass the metadata policy (400 invalid_meta). With byteSize, a stored object over the cap of the path’s kind is discarded and answered 413 too_large. The object is checked and sanitized in place first (allowlist and markup sniff, rasters always; 415 invalid_upload / sanitize_required / unsupported_type deletes it and frees the name; a tenant raster that doesn’t decode is invalid_upload too). The on-ingest recipes then run in this request, except on AWS with a queue, where the S3 upload trigger and the worker own them (see On-ingest processing); the response is the asset with publicUrl / previewUrl |
POST /api/media/ingest/svg |
{ filename, svg, tenant?, meta? }: the only way an SVG reaches the library on the web API (runtime/server/api/media/ingest/svg.post.ts; @tgmc/media-client ingestSvg). The admin sends the SVG it already sanitized; the route calls ingest({ kind: 'svg', preSanitized }) (true only for the admin), and the web sanitizer (createWebUploadSanitizer from @tgmc/image/sanitize-web) runs svgo on it again, then scans the result, before anything is stored or reserved. Only the sanitized bytes are stored; markup svgo leaves active, or that is not plain UTF-8 (another declared encoding, control characters), is 415 invalid_upload, and a type outside the allowlist 415 unsupported_type (for a tenant, a filename of another type is 415 kind_not_allowed). 400 for a missing filename or SVG text, 413 over 4 MiB; meta passes the metadata policy (400 invalid_meta) and meta.filename defaults to the filename. Answers the asset with publicUrl / previewUrl |
PATCH /api/media/assets/:id |
{ meta?, tags? }: a validated edit (updateAssetMeta(…, { validate: true })); 400 invalid_meta with the field issues, 404 unknown asset. Answers the asset without URLs |
DELETE /api/media/assets/:id |
?force=1 (admin only): hard cascade of the asset, its variants and blobs. An asset a published page uses is refused: 409 data: { code: 'in_use', pages: MediaUsagePage[] } (the full list, not capped: bounded by the site’s pages), nothing deleted; ?force=1 deletes it anyway (an audited admin override; a tenant’s is 403 admin_only). Only force=1 forces (0 or absent do not); any other value, a bare ?force or a repeat is 400 force must be 1. 404 unknown asset or another tenant’s, 409 on a conflict. Answers { deleted, forced } |
GET /api/media/assets/:id/usage |
The published pages that use the asset: { assetId, pages: MediaUsagePage[] } ([] when none; each page { pageType, pageId, pageLabel, url, state }). 404 unknown asset or another tenant’s |
POST /api/media/assets/:id/rename |
{ filename } (same extension): moves the original and every variant to the new name (rename); the old /m/ URLs stop working (no redirects; CloudFront invalidated). 409 name_conflict with a suggestion, 409 while a job is active, 400 blank or other extension, 404 unknown asset. Answers the asset with publicUrl / previewUrl plus usedBy: the pages that use it ([] when none) as a warning that their stored /m/ URLs stopped working, never a refusal; null when the usage read failed after the rename (logged as media.rename_usage_failed) |
POST /api/media/assets/:id/process |
Re-run processing (admin only, no body, idempotent): ready variants are kept, missing and failed ones are made again, meta is refreshed. { mode: 'async', processing } when queued for the worker, { mode: 'sync', report, processing } when it ran here. 404 unknown asset, 502 when SQS rejects the message |
POST /api/media/assets/:id/materialize |
{ role?, variant?, format?, recipe?, useDefaultThumb? }. variant (t/640/1280/1920) is a catalog variant at a stable key; recipe is a custom child; neither → t. p → 400. Re-materializing a catalog (variant, format) replaces the object in place and invalidates the CDN; the existing child stays ready (with its old meta) while the replacement job runs, and keeps serving if the job fails |
GET /api/media/assets |
kind, tenant, tag, limit, offset. Each asset carries publicUrl and previewUrl (see Asset URLs) |
GET /api/media/assets/:id |
{ asset, children, processing }; asset carries publicUrl and previewUrl; processing is each on-ingest step ({ variant, status: queued \| running \| ready \| failed \| not-started \| stalled, path, error }) |
PUT /api/media/_local-s3/<key> |
Filesystem backends only (404 on dynamodb and on Lambda). The local presigned PUT: no Bearer, the expires + sig query is the credential. See local presign mode |
GET/HEAD /m/<tenant>/<kind>/<file> |
Filesystem backends only (404 on dynamodb and on Lambda). Public, read-only CDN stand-in. See CDN stand-in |
Upload modes
resolveMediaIngestMode() picks the mode of presign and complete from the resolved data backend (same resolution as getMediaLibrary, including E2E_STORE_SYS_ENV), so the catalog and the blobs always sit in the same place. Docker stacks set MEDIA_TABLE + ASSETS_BUCKET even with DATA_BACKEND=sqlite|postgres; the backend, not those variables, decides.
| Backend | Mode | presign returns |
complete reads the object from |
|---|---|---|---|
dynamodb |
aws |
S3/MinIO presigned PUT (createPresignedIngest) |
S3BlobStore (head + streamed SHA-256) |
sqlite / postgres |
local |
PUT /api/media/_local-s3/pending/<assetId>/<key>?expires=&sig= (this origin) |
FsBlobStore (head + re-read SHA-256) |
dynamodb without MEDIA_TABLE + ASSETS_BUCKET is a 503. On Lambda (isOnLambda(): AWS_LAMBDA_FUNCTION_NAME set) local mode is always off, whatever backend resolves (isLocalMediaBackend() is false): media is DynamoDB + S3 there, like the library getMediaLibrary() opens, so presign / complete use aws mode (503 naming Lambda without the table and bucket), and the _local-s3 PUT and /m/** routes are 404. Everything else is identical in both modes: the name reservation and its 409 with a suggested name, the response shape, the four headers the PUT must send, create-only originals (412 on a second PUT), and the reservation + SHA-256 checks in complete (a missing object is 404). Async (queued) materialize stays AWS-only: with MEDIA_QUEUE_URL set, assertMediaAwsMode() returns 503 naming the resolved backend unless media is on AWS (dynamodb, or any backend on Lambda) with the table and bucket; without a queue, materialize runs synchronously against the active library in both modes.
Local presign mode
createLocalPresignedIngest (runtime/server/utils/media-local-s3.ts) signs, like the S3 presign, the private pending key pending/<assetId>/<key> (media § Name reservation): the object is stored at <MEDIA_LOCAL_ROOT>/blobs/pending/..., which /m/** never serves, until complete checks it, copies it to its key and deletes it. It signs an absolute URL on the request origin (X-Forwarded-Host / X-Forwarded-Proto honoured), valid 15 minutes like the S3 presign. The signature is HMAC-SHA256, keyed with MEDIA_LOCAL_SIGNING_SECRET (a random per-process secret when unset, so URLs die on restart), over the method, the key, expires, the size and the values of the four PRESIGN_REQUIRED_HEADERS. The size is len=<byteSize> when the presign was sized (the URL then carries &len=, so the length is signed like S3’s content-length), else the upload byte cap. The PUT route checks, in order:
- the key is a pending upload key (
pending/<assetId>/<original key>; a publicm/key,@variantkeys, traversal and anythingparsePendingUploadKeyrejects → 400); - the signature, compared in constant time (a different key,
len, Content-Type,Cache-Control,Content-Dispositionor a missingIf-None-Match: *→ 403SignatureDoesNotMatch, as on S3); - the expiry (403);
- with
len, a declaredContent-Lengthother thanlen(403SignatureDoesNotMatch, as S3 answers a different signed length); without it, a declaredContent-LengthoverMEDIA_LOCAL_UPLOAD_MAX_BYTES(413);
then streams the body into FsBlobStore.putStream with len (else MEDIA_LOCAL_UPLOAD_MAX_BYTES) as the cap (413 mid-stream; a chunked upload may see the connection close instead) as a create-only write (412 if the original exists), and answers 200 with the object’s ETag. With len, a streamed body that ends short is 400 IncompleteBody and nothing is stored, so the shim, like S3, only accepts exactly len bytes. The headers land in the sidecar, so the object is served exactly like a presigned S3 object.
Upload size cap
Every presigned upload kind has a byte cap (uploadCapBytes(kind) in @tgmc/media upload-caps.ts), overridable per kind with MEDIA_MAX_UPLOAD_BYTES_<KIND> (a positive integer; anything else keeps the default):
| Kind | Default | Variable |
|---|---|---|
image |
25 MiB (MAX_BYTES from @tgmc/image) |
MEDIA_MAX_UPLOAD_BYTES_IMAGE |
document |
10 MiB (MAX_PDF_SANITIZE_BYTES), every PDF |
MEDIA_MAX_UPLOAD_BYTES_DOCUMENT |
video |
500 MiB | MEDIA_MAX_UPLOAD_BYTES_VIDEO |
audio |
100 MiB | MEDIA_MAX_UPLOAD_BYTES_AUDIO |
model |
100 MiB | MEDIA_MAX_UPLOAD_BYTES_MODEL |
SVG never presigns (POST /api/media/ingest/svg has its own 4 MiB body limit).
- Presign. A request with
byteSizeis checked before any name is reserved: not a positive integer → 400, over the cap → 413data: { code: 'too_large', maxBytes }. The URL is then signed for exactly that length (S3content-length, the local shim’slen), so the PUT cannot send a larger or smaller body. The route logs one JSON line per sized presign,presign.sized({ kind, principal: 'admin' | 'tenant' },console.info). - Complete. A
byteSizein the body must be a positive integer (400), as on presign. With it, and on every tenantcomplete, the stored object (head) is checked against the cap of the path’s kind (not the body’skind); over it, the upload is discarded (library.discardUpload, reasontoo_large: the name stays held until the object is gone, see media § Name reservation) and answered 413too_large. If anothercompleteregistered the asset meanwhile, the discard is refused and the answer is 409. Complete does not compare the stored length withbyteSize: the signed length already did. - Expand phase (admin only).
byteSizeis optional for the admin for now: an unsized presign still works (signed for no length, as before) and logspresign.unsized({ kind },console.warn); an admin complete withoutbyteSizeskips the cap. A tenant must send it (Auth). The admin server andscripts/media-smoke.jssend it on both calls. A later step makes it required once no unsized presign is logged.
Admin preSanitized signature
preSanitized: true lets an admin PDF or MP4 skip the web’s sanitizer (the admin server already ran it). So that it takes more than the admin token, the admin signs each such upload with a secret it shares with the web, MEDIA_PRESANITIZE_SECRET, and sends the signature on complete as preSanitizedSig (@tgmc/media signPreSanitized; core/admin/server/utils/media-service.ts). The signature is HMAC-SHA256, base64url, over
v1\n<assetId>\n<path>\n<sha256 of the stored object, lowercase hex>
so it only fits that asset, that key and those bytes. complete checks it after reading the object’s SHA-256 (preSanitizedTrust / verifyPreSanitized, constant-time). Rasters and SVG never carry one: the flag doesn’t skip anything for them (upload sanitizing), so they ignore it and log nothing. A tenant’s flag is never honoured.
Expand phase. Nothing is refused unless a key is set and the signature is wrong. “Key” means MEDIA_PRESANITIZE_SECRET or MEDIA_PRESANITIZE_SECRET_PREVIOUS (trimmed; empty is unset). For an admin PDF or MP4 with preSanitized: true:
| Key on the web | preSanitizedSig |
Honoured | Log (on Lambda) | Log (off Lambda) |
|---|---|---|---|---|
| yes | valid | yes | presanitize.verified (info) |
presanitize.verified (info) |
| yes | wrong | no: the normal path, so 415 sanitize_required, the object is deleted and the name freed |
presanitize.bad_signature (warn) |
presanitize.bad_signature (warn) |
| yes | missing | yes | presanitize.unsigned (warn) |
none (today’s behaviour) |
| no | present or missing | yes (nothing can verify it) | presanitize.no_key (warn) |
none (today’s behaviour) |
Each event is one JSON line { evt, assetId, path }, never the signature or a key. presanitize.verified is the positive evidence for the enforce step. That step (Phase 7 S1-13) refuses an unsigned PDF or MP4 on Lambda, and one sent to a web without a key; it ships once production has run this for a week with presanitize.verified and no warnings. The admin sends preSanitizedSig only when its own MEDIA_PRESANITIZE_SECRET is set, so either side can be configured first.
Rotation. The web verifies against MEDIA_PRESANITIZE_SECRET, then MEDIA_PRESANITIZE_SECRET_PREVIOUS. Deploy the web with the new value in the first and the old one in the second, rebuild the admin with the new value, then clear _PREVIOUS (cicd § Admin preSanitized secret).
On Lambda means isOnLambda() (runtime/server/utils/media-library.ts): AWS_LAMBDA_FUNCTION_NAME is set. docker:dev / docker:local on DynamoDB are not on Lambda; isLocalMediaBackend() and assertMediaAwsMode() use the same helper.
CDN stand-in (/m/**)
On the filesystem backends GET/HEAD /m/<tenant>/<kind>/<file> serves FsBlobStore objects at the path CloudFront serves on AWS. Responses carry the sidecar Content-Type, Cache-Control: no-cache, Content-Disposition: inline; filename="…" (defaults for blobs without a sidecar), X-Content-Type-Options: nosniff, the ETag, Accept-Ranges: bytes and Content-Length. If-None-Match is a weak comparison over a list or * (W/"x" matches "x"; 304). A single GET byte range (bytes=a-b, a-, -n) gets a 206 with Content-Range (clamped to the object; 416 with bytes */size when unsatisfiable); several ranges, another unit or a malformed header serve the whole object, and If-Range allows the range only for the current ETag (strong comparison). Safari plays <video> only with 206 responses. Headers and body come from one opened file, so a variant overwritten mid-request never mixes generations. Unlike CloudFront’s one-year immutable, browsers revalidate every time (a cheap 304): a key gets new bytes in place (variants are overwritten, a deleted original can be uploaded again under its key) and nothing invalidates them. The ?v= content version of versioned URLs is ignored here: /m/pf/i/hero.png?v=1a2b3c4d serves the key. The sidecar still records the S3 Cache-Control. Only valid media keys resolve, so sidecars (*.meta.json), temp files and paths outside the blob root are 404; other methods are 405. Because it serves on the app origin, every response that is not passive media gets Content-Security-Policy: default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox, so an SVG, HTML, XHTML, XML or unknown-type object opened directly runs no script. The check uses the MIME essence (parameters stripped, trimmed, lowercased, so Image/SVG+XML; charset=utf-8 is SVG). Passive types are left alone: image/* except SVG, audio/*, video/*, model/*, font/* and application/pdf (Chrome will not render a PDF in a sandbox). This is a dev-only hardening; CloudFront serves media from its own origin and does not add it. On dynamodb the route is 404: CloudFront (AWS) or MinIO (Docker) serve m/* there.
The handler is createLocalMediaCdnHandler({ enabled, store }) (…/media-cdn); this module mounts it with isLocalMediaBackend() and the library’s FsBlobStore, and core/admin mounts it on its own local library (admin.md).
core/web/server/middleware/cdn.ts (the static-asset 302 to the CDN) leaves /m/… alone while local media is on, so the stand-in answers even when NUXT_APP_CDN_URL is set; otherwise it sends /m/… to mediaPublicBaseUrl(), not to the static-asset CDN, also when NUXT_APP_CDN_URL is unset (e.g. MinIO on Docker dynamodb); the static-asset CDN is the fallback only when no media base is known. Every /m/ object is redirected whatever its extension (documents included); outside /m/ the static extension list decides.
Public URLs
mediaPublicBaseUrl() (runtime/server/utils/media-public-url.ts) is where media is publicly readable; every media URL is that base + / + key (mediaPublicUrl(key)), e.g. /m/pf/i/manhattan-keyframe@t.webp on host dev, plus ?v=<sha8> for a stored object (mediaPublicUrl({ path, version }); see Asset URLs). core/web/server/middleware/cdn.ts keeps v (and only v) when it redirects a /m/ request to this base. The first match wins:
| When | Base |
|---|---|
MEDIA_PUBLIC_BASE_URL set |
That value, on every backend (SAM: the stack’s own CloudFront distribution) |
sqlite / postgres (never on Lambda) |
'' (same origin, served by /m/**), whatever CDN variables are set |
dynamodb, or anything on Lambda |
NUXT_APP_CDN_URL, else NUXT_PUBLIC_CDN_URL |
dynamodb without a CDN |
MEDIA_S3_PUBLIC_ENDPOINT + / + ASSETS_BUCKET (MinIO in Docker), else '' |
Trailing slashes are dropped. On the SAM test stack NUXT_APP_CDN_URL is the shared test CDN, which does not front the stack’s AssetsBucket, so the template sets MEDIA_PUBLIC_BASE_URL: https://${AssetsDistribution.DomainName} on test and production (scripts/sam-template.test.js pins it). On Lambda (AWS_LAMBDA_FUNCTION_NAME set) getMediaLibrary() is always DynamoDB + S3: a resolved sqlite / postgres backend without MEDIA_TABLE + ASSETS_BUCKET throws instead of writing to the Lambda filesystem.
Asset URLs
withMediaAssetUrls(asset, children) / withMediaAssetUrlsList(library, assets) (runtime/server/utils/media-asset-urls.ts) add two fields to the list, detail and complete responses:
publicUrl: the original, versioned with its content hash:mediaPublicObjectUrl(base, asset.path, sha8), e.g./m/pf/i/hero.png?v=1a2b3c4d(media § Versioned public URLs).previewUrl: what a grid tile shows, frommediaPreviewObject()in@tgmc/media(versioned the same way: a variant by itsmeta.sha256). Image and SVG: the readytchild (webp preferred), else the original. Audio and video: the original (players load it withpreload="metadata"). Model and document:null.
The list reads children only for image and SVG rows (one listChildren each; a failure falls back to the original).
On-ingest processing
Every new asset gets the on-ingest recipes (runOnIngestRecipes in @tgmc/media): meta (image size, LQIP, dominant colour; SVG size; PDF page count when pdf-lib is installed), then the catalog image variants t / 640 / 1280 / 1920 (webp, never wider than the original). Exactly one runner owns them per environment (onIngestOwner()), so an upload never has two concurrent runs:
| Environment | Owner | How |
|---|---|---|
Host dev (SQLite), docker:local / docker:dev, docker:test |
request |
The library’s onIngested hook (onIngestRecipesHook) runs them inside complete (and any ingest / registerRemoteAsset); docker:test sets no MEDIA_QUEUE_URL |
SAM test / production (dynamodb or Lambda + MEDIA_QUEUE_URL) |
worker |
complete neither runs nor queues them: the AssetsBucket ObjectCreated notification queues every new original and the media worker runs them (media-aws) |
A recipe failure never fails the upload: per-variant failures mark that child failed, an undecodable source records meta.processingError, and a hook error is audited (asset.on_ingest_failed). POST …/process re-runs them through the same owner (an on-ingest SQS message on AWS). onIngestProcessing(library, asset) builds the detail’s processing. The admin’s local library uses the same hook (admin.md).
Page-load cost
The module is server-only: it adds runtime/server (the /api/media/* handlers, the /m/** stand-in and utils) and no plugin, middleware or client code, so no page requests anything from it (measured on /, /work, /gallery, /about at 375 and 1280 px: 0 media requests, 0 bytes of client JS). The web app’s own server/middleware/cdn.ts runs on every request and calls isLocalMediaBackend() / mediaPublicBaseUrl(); both only read env (a request costs no store, client or file access).
Its cost is at server start: the web Nitro build sets inlineDynamicImports, so every static import in the server bundle loads at boot, including what the media routes need. Measured on the local build (Windows, Node 26, median of 5 to 7 boots): spawn to listening 688 ms before, 577 ms after sanitizeSvg began importing svgo on first use (svgo alone ~150 ms). @tgmc/media-postgres is in the bundle but pg is not evaluated at boot: its pool imports pg on the first query (createLazyPgPool), guarded by media-postgres/tests/lazy-pool.spec.ts and a media-library-env.spec.ts case that the sqlite and dynamodb paths never load it (the web app’s own message and post stores still import pg statically). What still loads at boot only for media: the S3, SQS and CloudFront SDK modules and the S3 presigner of @tgmc/media-aws (~50 ms on top of the DynamoDB client the web app loads anyway). The client objects are now created on first use and shared for the process (sharedS3Client, sharedCloudFrontClient, the SQS client; review M4: complete and presign used to build a new S3 client, and every invalidation a CloudFront client, per request), with bounded retries (maxAttempts: 3) and timeouts (3 s connect, 30 s socket idle; MEDIA_AWS_CLIENT_DEFAULTS). Loading the SDK modules themselves through a cached dynamic import (as svgo already is, which measurably left the boot path) would remove the module cost from cold starts; it stays in the TODO.
Env
| Variable | Role |
|---|---|
ADMIN_TOKEN / NUXT_ADMIN_TOKEN |
The admin Bearer on /api/media/* (Auth; must not start with tgmc_mt_); not on the presigned PUT /api/media/_local-s3/<key>, whose expires + sig query is the credential |
DATA_BACKEND |
dynamodb → AWS adapters (needs MEDIA_TABLE + ASSETS_BUCKET, else throws); sqlite → local SQLite/FS; postgres → Postgres catalog (DATABASE_URL) + FS blobs. Unset: SYS_ENV default |
DATABASE_URL / NUXT_DATABASE_URL |
postgres only: the media catalog, jobs, audit and usage list (@tgmc/media-postgres; NUXT_ wins; unset, or not postgres:// / postgresql:// such as the SQLite file: default, throws). Same URL as the posts store |
MEDIA_LOCAL_ROOT |
Local root when the backend is not dynamodb (default .data/media; docker:local / docker:dev set /app/data/media): media.sqlite (not on postgres) plus the blobs/ tree served at /m/** |
MEDIA_LOCAL_SIGNING_SECRET |
HMAC key for local presigned PUTs; unset → random per process (URLs stop working after a restart). Set it when several processes serve one origin, or to keep URLs valid across restarts |
MEDIA_LOCAL_UPLOAD_MAX_BYTES |
Byte cap of an unsized local presigned PUT (default 104857600, 100 MiB); a sized one is capped at its signed len |
MEDIA_MAX_UPLOAD_BYTES_<KIND> |
Per-kind presigned upload cap (IMAGE, DOCUMENT, VIDEO, AUDIO, MODEL); see Upload size cap |
MEDIA_PRESANITIZE_SECRET / MEDIA_PRESANITIZE_SECRET_PREVIOUS |
Keys that verify the admin’s preSanitizedSig (the second only during a rotation); see Admin preSanitized signature. SAM MediaPresanitizeSecret / MediaPresanitizeSecretPrevious |
MEDIA_PUBLIC_BASE_URL |
Media public base on every backend, checked first by mediaPublicBaseUrl(). SAM sets it to the stack’s own CloudFront distribution |
NUXT_APP_CDN_URL / NUXT_PUBLIC_CDN_URL |
Media public base on dynamodb when MEDIA_PUBLIC_BASE_URL is unset; ignored on the filesystem backends |
MEDIA_TABLE / NUXT_MEDIA_TABLE |
DynamoDB table → use @tgmc/media-aws |
ASSETS_BUCKET / NUXT_ASSETS_BUCKET |
S3 assets bucket (required with MEDIA_TABLE) |
MEDIA_QUEUE_URL / NUXT_MEDIA_QUEUE_URL |
Optional SQS queue: async materialize and Re-run processing. On AWS it also hands on-ingest processing to the S3 upload trigger + worker (complete stops running it) |
ASSETS_DISTRIBUTION_ID / NUXT_ASSETS_DISTRIBUTION_ID |
Optional CloudFront invalidation on delete |
NUXT_AWS_REGION / AWS_REGION |
AWS region for adapters |
AWS_ENDPOINT_URL_DYNAMODB |
DynamoDB endpoint override (DynamoDB Local); unset on AWS |
MEDIA_S3_ENDPOINT / AWS_ENDPOINT_URL_S3 |
S3 API endpoint the server uses (MinIO, http://minio:9000) |
MEDIA_S3_FORCE_PATH_STYLE |
1 → path-style S3 addressing (MinIO needs it) |
MEDIA_S3_PUBLIC_ENDPOINT |
Host presigned URLs are signed for (http://localhost:4420); with ASSETS_BUCKET, the media public base in Docker when no CDN URL is set |
The endpoint variables exist for the docker:test stack (DynamoDB Local + MinIO) and are read by mediaAwsEndpointsFromEnv() in @tgmc/media-aws, so the web routes and the SQS worker resolve them identically. The global AWS_ENDPOINT_URL is ignored on purpose (in docker:test it names DynamoDB Local). mediaS3Options() / mediaPresignOptions() in runtime/server/utils/media-library.ts feed S3BlobStore (complete route) and createPresignedIngest (presign route).
Requirements: docs/plans/2026-09-22-004-feat-media-host-adapters-plan.md.