@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;
}| Option | Purpose |
|---|---|
basePath | Where the SPA is served. Keep it out of an /api prefix so it reads as a UI, not an endpoint. |
apiBasePath | Where 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. |
actions | Enables the destructive endpoints (delete object/record, copy/move, abort upload). The read API is always available. |
authorize | Who may use the console (page, assets and JSON API) — see Access. |
decorators | Class decorators applied to every console controller, before authorize runs: authentication guards, throttling. |
routes | false mounts no controller, for serving the console from your own — see Mount it yourself. Default true. |
imports | Modules providing the dependencies of a guard you pass through decorators. |
objectInsights | Annotate an object in the preview with what your app knows about it — see Object insights. |
objectUrls | Whether an object's reported url is presigned straight to the store or routed through this server — see Reaching an object's bytes. |
devTools | Serve the console's reads (and, with actions, two of its actions) as MCP tools. Default: on when routes is not false. |
viewer | Who 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. |
signOut | The 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',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
| Result | API call (fetch) | Page navigation (GET, Accept: text/html) |
|---|---|---|
true / { allowed: true } | allowed | allowed |
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 throw | 403 (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.
| Renderer | Opened for | How it reads |
|---|---|---|
| Image / video / audio | image/*, video/*, audio/* and the usual extensions | The object's own URL |
application/pdf, .pdf | Streamed 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 | |
| Text | text/*, .txt .json .csv .tsv .log .xml .yaml .sql | Head sample (8 MB), rendered raw, as pretty JSON, or as a CSV/TSV grid |
| Markdown | text/markdown, .md | Head sample, rendered and sanitized, with a source toggle |
| NDJSON | .ndjson .jsonl | Head sample, one object per line, columns unioned across rows |
| Spreadsheet | .xlsx .xls .xlsm .ods | Whole file (a workbook is a zip and can't be sampled), capped at 15 MB |
| SQLite | .sqlite .sqlite3 .db | Byte ranges — the database is queried in place, never downloaded |
| Parquet | .parquet | Byte ranges — footer, then only the column chunks the visible rows need |
| Archive | .zip .jar .whl .tar .tgz | Byte 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 .der | Parsed to subject/issuer/validity/SANs. Private key blocks are named and never rendered |
| Hex | anything else | Byte 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:
nullmeans "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.
resolveruns 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:
| Method | Returns | Notes |
|---|---|---|
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 }) | ObjectListResponse | One level of a disk — { data: files, folders, meta }. See Folders. |
objectDetail(disk, key) | ObjectDetailResponse | Size, 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 | undefined | The object as the response, through serveFile(): Range → 206, If-None-Match → 304, past the end → 416, missing → 404. |
putObject(disk, key, body, contentType?, contentLength?) | void | Streams an object onto the disk (no size cap, nothing buffered). Action. |
createFolder / deleteFolder | void | Create (a hidden .keep) / recursive delete. Action. |
copyObject / moveObject | void | Single-object copy/move, same disk or cross-disk (streamed). Action. |
moveFolder / copyFolder | void | Whole-subtree copy/move. Action. See Folders. |
listUploads({ disk?, prefix? }) | UploadListResponse | In-progress resumable sessions. |
uploadDetail(id) / abortUpload(id) | UploadDetailResponse / void | Inspect / cancel a session (abort is an action). |
listCollections() | CollectionsResponse | Per-collection counts + byte totals (uses MediaStore.aggregate). |
listLibrary({ collection?, disk?, cursor?, limit? }) | LibraryListResponse | Paginated media records, { data, meta } (uses MediaStore.list). |
libraryDetail(id) / deleteLibraryRecord(id) | LibraryDetailResponse / void | One 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() | Topology | What'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 + path | Query | Response |
|---|---|---|
GET disks | — | DiskListResponse — { data } |
GET disks/:disk/objects | prefix?, after?, first? (default 50, max 1000) | ObjectListResponse — { data: files, folders, meta } |
GET disks/:disk/object | key | ObjectDetailResponse |
GET disks/:disk/object/raw | key | raw bytes; inline for types that can't run script (images, PDF, audio, video, plain text), else attachment |
GET disks/:disk/object/download | key | raw bytes, Content-Disposition: attachment |
GET disks/:disk/object/insights | key | ObjectInsightsResponse |
GET uploads | filter[disk]?, filter[key][startsWith]? | UploadListResponse — { data } |
GET uploads/:id | — | UploadDetailResponse |
GET library/collections | — | CollectionsResponse — { data } |
GET library | filter[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 + path | Body / query |
|---|---|
DELETE disks/:disk/object | key (query) |
POST disks/:disk/copy | { from, to, toDisk? } |
POST disks/:disk/move | { from, to, toDisk? } |
POST disks/:disk/upload | key + type? (query); raw application/octet-stream body |
POST disks/:disk/folder | { prefix } |
DELETE disks/:disk/folder | prefix (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'
})| Value | url is | Use 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 neither | the browser can reach the store. The URL survives a copy-paste out of the console and needs nothing from this server. |
proxy | the console's own object/raw route, same-origin | the 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.
| Tool | Kind | Input |
|---|---|---|
media_list_disks | read | — |
media_list_objects | read | disk, prefix?, cursor?, limit? |
media_get_object | read | disk, key |
media_list_uploads | read | disk?, prefix?, cursor?, limit? |
media_get_upload | read | id |
media_list_collections | read | collection?, disk?, cursor?, limit? (without collection or disk: the collection summary) |
media_get_media | read | id |
media_abort_upload | action | id |
media_delete_objects | action, destructive | disk, 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,undefinedor a throw shows no user row. Omitted,request.useris read structurally: whatever your guards (decorators) already put there. Reading it never triggers an authentication.signOut:'/logout'(a POST form, with_csrfwhen the request hasreq.csrfToken()),{ href: '/logout' }(a link),{ action, csrfToken: (request) => token }(a POST form with your token), orfalse(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 preservedIt 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.