Aviary
Packages

@dudousxd/nestjs-media-dashboard

Standalone /media console — disks, live uploads, and the media library, behind one `authorize` option.

A bundled React SPA + JSON API you mount alongside MediaModule to browse the @nestjs/storage disks, watch live uploads, and inspect the media library — without writing an admin UI of your own. It reads the disks from StorageModule's Storage, and the multipart side-cars, store and upload sessions from MediaModule.

import { MediaDashboardModule } from '@dudousxd/nestjs-media-dashboard';

@Module({
  imports: [
    StorageModule.forRoot({ disks: { /* … */ } }),
    MediaModule.forRoot({ /* … */ }),
    MediaDashboardModule.forRoot({
      basePath: '/media',
      apiBasePath: '/api/media/console',
      // Who may use the console — see "Access". Without it, production answers 403.
      authorize: (ctx) => ctx.switchToHttp().getRequest().user?.isAdmin === true,
    }),
  ],
})
export class AppModule {}

Exclude both paths from any global /api prefix — the SPA (basePath) is a page route, not an endpoint.

MediaDashboardModule.forRoot(options)

interface MediaDashboardOptions {
  basePath?: string;       // default '/media'
  apiBasePath?: string;    // default '<basePath>/api'
  actions?: boolean;       // enable delete/copy/move/abort — default false (read-only)
  authorize?: ConsoleAuthorize;              // who may use the console — see "Access"
  imports?: DynamicModule['imports'];        // DI resolution path for a decorator guard's deps
  decorators?: ClassDecorator[];             // applied to every console controller, e.g. UseGuards(...)
  routes?: boolean;                           // false → mount no controller (mount them yourself)
  objectInsights?: ObjectInsightProvider[];  // host context shown in the preview
  objectUrls?: 'auto' | 'proxy';             // presigned store URLs, or same-origin — default 'auto'
  devTools?: boolean;                         // MCP tools on /mcp/aviary — default: on when routes are mounted
  viewer?: (req) => { label: string; email?: string; role?: string } | null | undefined; // sync or async
  signOut?: string | { href: string } | { action: string; csrfToken?: (req) => string | undefined } | false;
}
OptionPurpose
basePathWhere the SPA is served. Keep it out of an /api prefix so it reads as a UI, not an endpoint.
apiBasePathWhere the JSON API is mounted (what the SPA fetches). Put it under your app's /api prefix so it inherits the app's proxy rules.
actionsEnables the destructive endpoints (delete object/record, copy/move, abort upload). The read API is always available.
authorizeWho may use the console (page, assets and JSON API) — see Access.
decoratorsClass decorators applied to every console controller, before authorize runs: authentication guards, throttling.
routesfalse mounts no controller, for serving the console from your own — see Mount it yourself. Default true.
importsModules providing the dependencies of a guard you pass through decorators.
objectInsightsAnnotate an object in the preview with what your app knows about it — see Object insights.
objectUrlsWhether an object's reported url is presigned straight to the store or routed through this server — see Reaching an object's bytes.
devToolsServe the console's reads (and, with actions, two of its actions) as MCP tools. Default: on when routes is not false.
viewerWho the sidebar footer says is signed in: (request) => ({ label, email?, role? }), sync or async. Default: request.user, read structurally. See Signed-in user and sign-out.
signOutThe sidebar footer's sign-out: '/logout' | { href } | { action, csrfToken? } | false. Default: the account.signOut an account console announced, else none.

MediaDashboardModule.forRootAsync(options) mirrors this, building objectInsights through an injected useObjectInsights(...deps) factory (inject lists the deps). authorize, decorators, routes, actions and the mount paths stay static fields on the async options object, since they shape the routes when the module is built.

Access

With tenancy on, the library and uploads views follow the request's tenant like the rest of media: a record or session of another tenant is a 404, as is a missing one. That includes delete record and cancel upload, where the library's own delete()/abort() are a silent no-op. The object browser lists raw disk keys and is not scoped.

authorize decides who may use the console. It runs on every console request: the page, its assets, the read API and the actions. It runs after your decorators and global guards, so your authentication has already set request.user.

import { UseGuards } from '@nestjs/common';
import { AuthenticationGuard } from '@nestjs/authentication';

MediaDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard)], // sign-in: your app's own
  authorize: (ctx) => ctx.switchToHttp().getRequest().user?.isAdmin === true,
});

This is the console's access. It is a different option on a different module from MediaModule's authorize(user, action, subject) hook, which checks MediaService reads and writes. The upload routes keep their own decorators / routes.

The five forms

// 1. Inline function
authorize: (ctx) => ctx.switchToHttp().getRequest().user?.isAdmin === true,

// 2. A class: an @Injectable() that implements ConsoleAuthorizer (constructor injection works)
authorize: ConsoleAccess,

// 3. A lazy import of that class (its default export)
authorize: () => import('./console-access.js'),

// 4. An @nestjs/authorization policy: policy[ability](user)
authorize: { policy: ConsolePolicy, ability: 'view' },

// 5. A gate name registered with @dudousxd/nestjs-authz's AuthzModule
authorize: 'console.media',
console-access.ts
import { type ExecutionContext, Injectable } from '@nestjs/common';
import type { ConsoleAuthorizer } from '@dudousxd/nestjs-media-dashboard';

@Injectable()
export default class ConsoleAccess implements ConsoleAuthorizer {
  constructor(private readonly audit: AuditService) {}

  async authorize(ctx: ExecutionContext) {
    const user = ctx.switchToHttp().getRequest().user;
    if (!user) return { redirectTo: '/login?next=/media' };
    await this.audit.record('console.open', user.id);
    return user.roles.includes('admin');
  }
}

The policy form needs @nestjs/authorization installed (an optional peer) and AuthorizationModule.forRoot() imported in the app; without either, the app fails at boot and says so. It reads the user with AuthorizationModule's getUser (default: request.user); null, false or no user is a guest, so a denial is a 401 instead of a 403. The gate-name form needs @dudousxd/nestjs-authz's AuthzModule; without it the app fails at boot and says so. The authz package also exports authorizeByRoles({ roles }) and authorizeByPermission(permission).

What authorize returns

ResultAPI call (fetch)Page navigation (GET, Accept: text/html)
true / { allowed: true }allowedallowed
false / { allowed: false }403 { "error": "forbidden" }403 "Access denied" page
{ allowed: false, reason: 'unauthenticated' }401 { "error": "unauthenticated" }401 "Sign in required" page
{ redirectTo: '/login' }401 { "error": "unauthenticated", "redirectTo": "/login" }302 to /login
a throw403 (logged at warn)403

The bundled SPA shows an access-denied state when the API answers 403. When it gets a 401 with redirectTo, it sends the browser there.

A shared token

authorizeByToken allows a request whose Authorization: Bearer <token> header matches (compared in constant time). Anything else is unauthenticated. The header is the only place it looks, so ?token= does nothing. An empty or missing token throws when you call it, at config time.

import { authorizeByToken } from '@dudousxd/nestjs-media-dashboard';

MediaDashboardModule.forRoot({ authorize: authorizeByToken({ token: process.env.CONSOLE_TOKEN }) });

A browser navigation sends no Authorization header, so this suits API clients and scripts more than the SPA.

An allow can also name who it let in: { allowed: true, caller: 'user:42' }. The MCP tools log that name as the caller of each call. Never put a secret in it. authorizeByToken names its caller token:<hash>.

A token or a session: anyAuthorize

anyAuthorize(...forms) allows a request when any of its forms allows it. If none does, the result is unauthenticated when any form said so, and forbidden otherwise. Each form is any of the five authorize forms.

import { anyAuthorize, authorizeByToken } from '@dudousxd/nestjs-media-dashboard';

MediaDashboardModule.forRoot({
  authorize: anyAuthorize(authorizeByToken({ token: process.env.CONSOLE_TOKEN }), AdminAuthorizer),
});

Without authorize

  • Outside production (NODE_ENV !== 'production') the console is open.
  • In production every request (page, assets, API) answers 403 { "error": "forbidden" }.
  • Either way, one warning is logged at boot:
[@dudousxd/nestjs-media-dashboard] console has no `authorize` configured: it is open outside production and denies every request in production. Set `authorize` in MediaDashboardModule.forRoot().

decorators don't count as authorize: an auth guard in decorators alone still leaves production answering 403.

decorators

Class decorators applied to every controller the console mounts, before authorize runs. Use them for authentication, throttling and the like:

MediaDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard)],
  authorize: { policy: ConsolePolicy, ability: 'view' },
});

Each registration decorates fresh subclasses of the controllers, so decorators never leak from one registration into another. imports adds modules that provide a decorator guard's dependencies.

Every console controller is marked @Can.Anyone()-open ('authorization:can-anyone' metadata), so @nestjs/authorization's deny-by-default global AuthorizationGuard lets it through and authorize decides. A Can(...) you pass in decorators is still checked.

authorize fronts BOTH the page (a full-page GET to basePath) and the JSON API (the SPA's fetch calls, which send cookies with credentials: 'same-origin'). A full-page navigation carries only cookies, never an Authorization header. If your authentication only reads a bearer token, every browser visit to the console is a guest. Authenticate the console from a cookie.

Mount it yourself

routes: false registers no console controller. Every provider keeps working and is exported (MediaConsoleService, the resolved paths and the resolved authorize). Serve the console by extending the exported controllers and apply UseConsoleAuthorize() so authorize still decides access. Keep basePath/apiBasePath equal to where you mount them, since the SPA reads both.

List @UseConsoleAuthorize() above your authentication guard. Nest applies class decorators bottom-up, so the guard listed lower runs first and sets request.user before authorize decides.

import { Controller, Module, UseGuards } from '@nestjs/common';
import {
  MediaConsoleActionsController,
  MediaConsoleReadController,
  MediaDashboardModule,
  MediaDashboardUiController,
  UseConsoleAuthorize,
} from '@dudousxd/nestjs-media-dashboard';

@UseConsoleAuthorize()
@UseGuards(AuthenticationGuard)
@Controller('media')
export class ConsolePageController extends MediaDashboardUiController {}

@UseConsoleAuthorize()
@UseGuards(AuthenticationGuard)
@Controller('media/api')
export class ConsoleApiController extends MediaConsoleReadController {}

@UseConsoleAuthorize()
@UseGuards(AuthenticationGuard)
@Controller('media/api')
export class ConsoleActionsController extends MediaConsoleActionsController {} // only with `actions: true`

@Module({
  imports: [
    MediaDashboardModule.forRoot({
      basePath: '/media',
      apiBasePath: '/media/api',
      routes: false,
      authorize: { policy: ConsolePolicy, ability: 'view' },
    }),
  ],
  controllers: [ConsolePageController, ConsoleApiController, ConsoleActionsController],
})
export class AppModule {}

UseConsoleAuthorize() applies ConsoleAuthorizeGuard and ConsoleAuthorizeFilter together: the JSON denials, the 302 for redirectTo, and the "Access denied" and "Sign in required" pages. The subclasses inherit every route and the constructor's injection, so they need no constructor of their own. Without authorize, the boot warning and the production 403 apply here too.

Migrating from the production boot refusal

A console mounted with no decorators in production no longer refuses to boot. It boots, answers 403 to every request, and logs the warning above. decorators no longer count as protection. Set authorize.

Before

MediaDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard), Can(MediaPolicy, 'console')],
});

After

MediaDashboardModule.forRoot({
  decorators: [UseGuards(AuthenticationGuard)],
  authorize: { policy: MediaPolicy, ability: 'console' },
});

A self-mounted console (routes: false) that used @Can(MediaPolicy, 'console') on its own controllers keeps working as it is. To have authorize decide instead, apply UseConsoleAuthorize() as shown above.

Previews

Clicking Preview on an object opens it inline, with a renderer chosen from its content type first, its filename second, and the broad image/*-style families last. The name usually beats the label: an object uploaded to S3 without an explicit type arrives as application/octet-stream, which describes nothing.

RendererOpened forHow it reads
Image / video / audioimage/*, video/*, audio/* and the usual extensionsThe object's own URL
PDFapplication/pdf, .pdfStreamed inline through the same-origin /raw route (PDF is one of the types serveFile() serves inline), so a signed URL carrying Content-Disposition: attachment still renders instead of downloading
Texttext/*, .txt .json .csv .tsv .log .xml .yaml .sqlHead sample (8 MB), rendered raw, as pretty JSON, or as a CSV/TSV grid
Markdowntext/markdown, .mdHead sample, rendered and sanitized, with a source toggle
NDJSON.ndjson .jsonlHead sample, one object per line, columns unioned across rows
Spreadsheet.xlsx .xls .xlsm .odsWhole file (a workbook is a zip and can't be sampled), capped at 15 MB
SQLite.sqlite .sqlite3 .dbByte ranges — the database is queried in place, never downloaded
Parquet.parquetByte ranges — footer, then only the column chunks the visible rows need
Archive.zip .jar .whl .tar .tgzByte ranges — the ZIP central directory lives at the end of the file, so listing a 2 GB archive costs tens of KB. Clicking a text entry reads and inflates just that entry. tar/tar.gz have no index and are listed from a labelled head sample
Certificate.pem .crt .cer .derParsed to subject/issuer/validity/SANs. Private key blocks are named and never rendered
Hexanything elseByte ranges — a windowed hex + ASCII dump you can seek through

The last row is the important one: there is no "no preview available" state any more. Whatever the console cannot identify is still bytes, and bytes render as hex.

The range-backed renderers read Range requests answered by @nestjs/storage's serveFile(); every StorageDisk serves byte ranges, so every disk gets them.

Everything past the plain media types is code-split: opening the console does not load the SQLite engine, the Parquet reader, SheetJS, the inflater, the X.509 parser or the Markdown renderer. Each arrives on the first preview that needs it.

Object insights

The console can describe a file only as storage sees it: key, size, content type, last modified. Everything that makes the file mean something lives in your app — which knowledge base indexed this PDF, which work order this scan belongs to, whether processing has run. objectInsights is the seam for handing that back:

MediaDashboardModule.forRoot({
  objectInsights: [
    {
      id: 'knowledge-base',
      async resolve({ disk, key }) {
        if (!key.startsWith('rag/')) return null; // not ours — render nothing
        const doc = await ingestionLog.get(key);
        if (!doc) return null;
        return {
          title: 'Knowledge base',
          facts: [
            { label: 'Status', value: doc.status },
            { label: 'Chunks', value: String(doc.chunks ?? 0) },
          ],
          links: [{ label: 'Open in the control panel', href: `/ctrl/rag/${doc.collection}` }],
        };
      },
    },
  ],
});

Use forRootAsync({ useObjectInsights, inject }) when a provider needs injected services — which is the usual case, since a provider that says anything interesting needs a repository.

Data, not components. A provider returns an ObjectInsight — title, plus optional facts (label/value rows), links and a one-line note — and the console renders it. It is not a slot you draw into: the console ships as a prebuilt SPA bundle, so there is nowhere for a host to inject React. The cost is a fixed vocabulary; the benefit is that the console stays ignorant of every domain plugged into it.

Three behaviours worth knowing:

  • null means "nothing to say" and renders nothing. Most providers care about one key prefix, so this is the common return.
  • A provider that throws is skipped, logged server-side, and the others still render. Annotation must never be able to stop an admin opening a file.
  • resolve runs on every preview, so keep it to one indexed lookup. Providers run concurrently.

Link hrefs must be relative (/ctrl/...) or http(s). Protocol-relative (//host) and other schemes (javascript:, data:) are dropped rather than rendered — the guard for a provider that interpolated user-supplied text into a URL.

Programmatic access with MediaConsoleService

Everything the console UI does, it does through one injectable — MediaConsoleService. It's the read + action logic behind the JSON API, and because MediaDashboardModule re-exports it you can inject it into your own code (a cron that prunes stale uploads, a support tool, a custom admin screen) without going through HTTP:

import { MediaConsoleService } from '@dudousxd/nestjs-media-dashboard';

@Injectable()
export class HousekeepingService {
  constructor(private readonly console: MediaConsoleService) {}

  async report() {
    const { data: disks } = await this.console.listDisks();
    const topology = this.console.topology(); // { hasStore, hasUploads, disks, actions }

    for (const disk of disks) {
      const { data: files, folders, meta } = await this.console.listObjects(disk.name, { prefix: '' });
      // …walk folders, page with `{ cursor: meta.nextCursor }`…
    }

    // Library (needs a MediaStore that implements the query SPI — see Custom store)
    const { data: records, meta } = await this.console.listLibrary({ collection: 'gallery', limit: 100 });
  }
}

It resolves Storage (from StorageModule), the multipart side-cars, the MediaStore, and the upload-session store as optional dependencies, so a host missing any of them still boots — each method degrades to an empty shape ({ data: [] }, …) instead of throwing. The full surface:

MethodReturnsNotes
listDisks()Promise<DiskListResponse>Registered disks + each one's capabilities, computed by core's diskCapabilities() from the disk and its side-car.
listObjects(disk, { prefix, cursor, limit })ObjectListResponseOne level of a disk — { data: files, folders, meta }. See Folders.
objectDetail(disk, key)ObjectDetailResponseSize, content type, and a URL: the public one, else a signed one, else the console's /raw route.
serveObject(disk, key, { req, res, disposition?, filename? })StreamableFile | undefinedThe object as the response, through serveFile(): Range → 206, If-None-Match → 304, past the end → 416, missing → 404.
putObject(disk, key, body, contentType?, contentLength?)voidStreams an object onto the disk (no size cap, nothing buffered). Action.
createFolder / deleteFoldervoidCreate (a hidden .keep) / recursive delete. Action.
copyObject / moveObjectvoidSingle-object copy/move, same disk or cross-disk (streamed). Action.
moveFolder / copyFoldervoidWhole-subtree copy/move. Action. See Folders.
listUploads({ disk?, prefix? })UploadListResponseIn-progress resumable sessions.
uploadDetail(id) / abortUpload(id)UploadDetailResponse / voidInspect / cancel a session (abort is an action).
listCollections()CollectionsResponsePer-collection counts + byte totals (uses MediaStore.aggregate).
listLibrary({ collection?, disk?, cursor?, limit? })LibraryListResponsePaginated media records, { data, meta } (uses MediaStore.list).
libraryDetail(id) / deleteLibraryRecord(id)LibraryDetailResponse / voidOne record + variant URLs / delete (delete is an action).
search(q, limit, page){ title, subtitle?, href }[]Files matching q, as the console search shows them. See Searching every console.
topology()TopologyWhat's wired: { hasStore, hasUploads, disks, actions }.

Library methods need the query SPI

listCollections/listLibrary require a MediaStore that implements the optional count/aggregate/list methods. The four bundled ORM stores do; a custom store returns empty shapes until it adds them — see the MediaStore query SPI.

The JSON API

The SPA talks to the service over a small JSON API mounted at apiBasePath. It's split across two controllers, and every route below is relative to apiBasePath (e.g. /media/api). The read controller is always mounted; the action controller only when actions: true.

The response shapes are exported as types — see the client subpath.

Lists follow the Aviary list API. Rows are always under data. A paged list adds the cursor envelope meta: { nextCursor, prevCursor, hasNext, hasPrev }: pass meta.nextCursor back as after, and set the page size with first. These lists page forward only, so before/last answer 400. Filters are filter[field]=value or filter[field][op]=value; an unknown field or operator answers 400.

Read endpoints

Method + pathQueryResponse
GET disks—DiskListResponse — { data }
GET disks/:disk/objectsprefix?, after?, first? (default 50, max 1000)ObjectListResponse — { data: files, folders, meta }
GET disks/:disk/objectkeyObjectDetailResponse
GET disks/:disk/object/rawkeyraw bytes; inline for types that can't run script (images, PDF, audio, video, plain text), else attachment
GET disks/:disk/object/downloadkeyraw bytes, Content-Disposition: attachment
GET disks/:disk/object/insightskeyObjectInsightsResponse
GET uploadsfilter[disk]?, filter[key][startsWith]?UploadListResponse — { data }
GET uploads/:id—UploadDetailResponse
GET library/collections—CollectionsResponse — { data }
GET libraryfilter[collection]?, filter[disk]?, after?, first? (default 50, max 200)LibraryListResponse — { data, meta }, oldest first
GET library/:id—LibraryDetailResponse
GET topology—Topology
GET consoles—the other Aviary consoles this viewer may open (see Switching between consoles)

prefix on disks/:disk/objects is the folder being listed, part of the resource like the disk, not a filter: it decides which folders come back next to the files. An after on disks/:disk/objects that is not a cursor a previous page returned answers 400 (InvalidListingCursorError), not 500.

Actions

Present only with actions: true. All return 204 No Content. On copy/move routes the :disk in the path is the source; the JSON body's optional toDisk names a cross-disk destination.

Method + pathBody / query
DELETE disks/:disk/objectkey (query)
POST disks/:disk/copy{ from, to, toDisk? }
POST disks/:disk/move{ from, to, toDisk? }
POST disks/:disk/uploadkey + type? (query); raw application/octet-stream body
POST disks/:disk/folder{ prefix }
DELETE disks/:disk/folderprefix (query)
POST disks/:disk/move-folder{ from, to, toDisk? }
POST disks/:disk/copy-folder{ from, to, toDisk? }
POST uploads/:id/abort—
DELETE library/:id—

The folder routes are covered in depth on the Folders page.

Reaching an object's bytes

There are two ways the console gets at a file, and they answer different questions.

Downloading — the Download button on a file row, in the preview header, and on a library record — always goes through GET disks/:disk/object/download, this server's own same-origin route. It answers with Content-Disposition: attachment named after the key's last segment (with the RFC 6266 filename* form for a non-ASCII name), and it honours Range, so an interrupted download of a large object resumes rather than restarting. It is a read: it needs no actions: true.

Being same-origin is the point. Saving a file is the console's own action, so it has to work on a host whose browser cannot reach the object store at all — no network route to the bucket, no CORS grant, or a policy against client-to-store traffic.

Opening — the Open ↗ link, and an image variant's src — uses the url reported by GET disks/:disk/object and GET library/:id. That one is configurable:

MediaDashboardModule.forRoot({
  objectUrls: 'proxy', // default: 'auto'
})
Valueurl isUse it when
auto (default)the disk's public URL when it has a publicUrl; else a signed, expiring URL (5 min); else the console's own object/raw route, for a disk that can do neitherthe browser can reach the store. The URL survives a copy-paste out of the console and needs nothing from this server.
proxythe console's own object/raw route, same-originthe browser cannot reach the store. The trade: the URL only means anything to a session that can reach this server, and every byte travels through it.

objectUrls does not affect downloading — that route is same-origin either way.

MCP tools

When the app imports the agent's MCP server (AgentMcpServerModule from @dudousxd/nestjs-agent-mcp-server), the console is also served as developer tools on its dev endpoint, /mcp/aviary. Each call is gated by this console's authorize and goes through MediaConsoleService, so tenancy applies as it does in the console. Object and variant URLs are never returned.

ToolKindInput
media_list_disksread—
media_list_objectsreaddisk, prefix?, cursor?, limit?
media_get_objectreaddisk, key
media_list_uploadsreaddisk?, prefix?, cursor?, limit?
media_get_uploadreadid
media_list_collectionsreadcollection?, disk?, cursor?, limit? (without collection or disk: the collection summary)
media_get_mediareadid
media_abort_uploadactionid
media_delete_objectsaction, destructivedisk, keys (1 to 100); idempotent: a missing key is reported as deleted

Lists return { items, next }; pass next back as cursor. An unknown disk, key or id is an error that says "not found". The two actions are offered only when the console has actions: true and the MCP server lists actions.

The tools are registered while the console's routes are mounted. devTools: true keeps them with routes: false, and devTools: false turns them off.

One console for several apps

federation turns this into a console for several apps: a switcher in the header picks the app (?app=<name>), and the console reads that app's library, upload sessions and disks in place from the app's own stores. See Federated console.

Switching between consoles

When the app mounts other Aviary consoles too (durable's Workflows, Telescope, Agents), the console's brand becomes a menu that lists the ones the viewer may open, and links to them. Each is listed only when its own authorize allows the viewer. That authorize then also runs once each time the page loads. With no other console, or none the viewer may open, the brand stays as it is. There is nothing to configure. The media console is listed in the other consoles' menus while its routes are mounted.

Searching every console

Press Ctrl/⌘+K, use the Search button in the topbar, or pick Search all consoles in the brand menu. The console's own pages are listed first. One query searches:

  • this console's files:
    • a library record by its exact id;
    • library records whose name or file name contains the text, ignoring case;
    • disk objects whose key starts with the text (invoices/2026/), on every disk.
  • every other Aviary console the viewer may open, for what each one searches (durable runs, Telescope entries, agent threads and runs).

Each console answers with up to 5 hits, grouped under its name, and gets 300 ms. A console that doesn't answer in time is left out, and the palette says some results are missing.

Hits respect tenancy like the rest of the console. Library records are those of the viewer's tenant. Disk objects carry no tenant, so they're searched only for a request that sees every tenant (tenancy off, or a system/all scope). With pathPrefix, a viewer of one tenant also finds the objects under their own t/<tenantId>/, and browses only that folder on the disks. Where a tenant is required and the viewer has none, the search finds nothing.

A hit opens the record or the file preview directly. The same links work by hand: /media#/library/<id> and /media#/disks/<disk>?prefix=<folder>&preview=<key>.

A preview's own view rides in the same link, so what you are looking at can be shared: a table preview (CSV, spreadsheet, NDJSON, Parquet, archive listing) keeps its filter and sort in q and sort (<column>.<asc|desc>, e.g. 2.desc), a spreadsheet its sheet in sheet, a Markdown file view=source. Typing the filter rewrites the current history entry; a sort, sheet or view pick adds one, so Back undoes it. Opening another file starts it fresh.

The endpoint is GET <apiBasePath>/consoles/search?q=, behind the console's own authorize. &console=<id> answers for that one console only (still behind its own authorize): the palette asks this console and each console in the switcher on its own, and shows each group as it answers.

Telling a probe from a visit

To list or search the other consoles, the switcher runs their authorize on the viewer's request. While it does, the request carries aviaryProbe = true. An authorize that writes an audit line for every visit can skip those:

authorize: (ctx) => {
  const req = ctx.switchToHttp().getRequest();
  if (req.aviaryProbe !== true) audit.log('console.open', req.user?.id);
  return req.user?.isAdmin === true;
},

Signed-in user and sign-out

The console runs on the shared Aviary console kit: a sidebar with the console switcher, the pages under LIBRARY (Library, Collections) and TRANSFERS (Uploads, Disks), and a footer with who is signed in, a light/dark toggle and a sign-out. Below 768px the sidebar is a drawer. The footer's user row and sign-out come from the server, in the page's config block; neither is required.

MediaDashboardModule.forRoot({
  authorize: ConsoleAccess,
  decorators: [UseGuards(AuthenticationGuard)],
  // Default: request.user, read structurally (fullName → name → email; role or the first of roles).
  viewer: (req) => ({ label: req.user.displayName, email: req.user.email, role: 'admin' }),
  // A POST form to /logout, with the token as `_csrf`:
  signOut: { action: '/logout', csrfToken: (req) => req.csrfToken() },
});
  • viewer: (request) => ({ label, email?, role? }), sync or async. null, undefined or a throw shows no user row. Omitted, request.user is read structurally: whatever your guards (decorators) already put there. Reading it never triggers an authentication.
  • signOut: '/logout' (a POST form, with _csrf when the request has req.csrfToken()), { href: '/logout' } (a link), { action, csrfToken: (request) => token } (a POST form with your token), or false (none). Omitted, the console uses the sign-out an account console announced on the Aviary consoles registry (account.signOut), else shows none.

Only same-origin paths (/x) ever reach the page. Both options are also on forRootAsync.

The typed browser client (/client subpath)

@dudousxd/nestjs-media-dashboard/client is a pure-types + tiny-runtime entry, safe to import into any browser bundle — it carries no NestJS. It exports mediaConsoleClient, a typed wrapper over every endpoint above (it sends cookies via credentials: 'same-origin', so authorize sees the page's session), plus every response type. This is what the bundled SPA uses, and what you'd import to build your own admin screen against the same API:

import {
  mediaConsoleClient,
  type MediaConsoleClient,
  type ObjectListResponse,
} from '@dudousxd/nestjs-media-dashboard/client';

const { data: disks } = await mediaConsoleClient.disks();
const page: ObjectListResponse = await mediaConsoleClient.objects('s3', { prefix: 'photos/' });
const more = await mediaConsoleClient.objects('s3', {
  prefix: 'photos/',
  after: page.meta.nextCursor ?? undefined,
});
const { record, variants } = await mediaConsoleClient.libraryRecord('abc123');

// Actions (need `actions: true` on the server)
await mediaConsoleClient.createFolder('s3', 'invoices/2024');
await mediaConsoleClient.moveObject('s3', 'a/x.jpg', 's3', 'b/x.jpg');
await mediaConsoleClient.uploadObject('s3', 'imports/data.csv', file); // raw bytes, MIME preserved

It also carries a few browser-only conveniences the raw API doesn't: objectRawUrl(disk, key) (a same-origin inline URL to embed a preview a signed cross-origin URL would force-download), objectTextHead(disk, key, maxBytes) (sample the head of a large text file without pulling it all down), objectBytes(disk, key) (fetch raw bytes for binary previews), and objectRange(disk, key, start, end) (fetch one byte range — end inclusive). A 401 or 403 from the API throws a ConsoleAccessError (status, redirectTo) and is reported to onConsoleAccessDenied(listener); a 401 with redirectTo also sends the browser there. objectRange throws if the server answers 200 instead of 206: a proxy that strips the Range header would otherwise stream the entire object into what the caller believes is a 64 KB page. MediaConsoleClient is the type of the whole client object, handy for wrapping or mocking it.

By default it fetches from /media/api; the UI controller injects the real base at runtime via window.__MEDIA_API__ / window.__MEDIA_BASE__, so a non-default apiBasePath is picked up automatically.

MediaConsoleApiModule

MediaDashboardModule is the batteries-included mount — SPA plus API at fixed paths. Underneath it sits MediaConsoleApiModule, the API-only dynamic module that holds the read/action controllers and MediaConsoleService. MediaDashboardModule composes it (and re-exports it, which is why MediaConsoleService is injectable in importers). You rarely register it yourself, but it's exported for hosts that serve the SPA their own way (a separate static host, a different framework) and only want the JSON API wired into Nest with custom routing:

import { MediaConsoleApiModule } from '@dudousxd/nestjs-media-dashboard';

Its register() takes the same building blocks MediaDashboardModule feeds it — actions, objectUrls, authorize, decorators, routes and imports — and exports MediaConsoleService. Access works the same way, and the boot warning names MediaConsoleApiModule.register(). Prefer MediaDashboardModule.forRoot/forRootAsync unless you specifically need to own the mount.

Peer dependencies

@dudousxd/nestjs-media-core, @nestjs/storage (>=0.0.5 <0.1.0), @nestjs/common / @nestjs/core (^12.1), and rxjs. @nestjs/authorization (>=0.1.3 <0.2.0) is optional: only the { policy, ability } form of authorize needs it. The bundled SPA ships its own React copy — no extra frontend install needed.

On this page