@adonis-agora/media
Version:
Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a
939 lines • 47.6 kB
JavaScript
import { readFile } from 'node:fs/promises';
import { basename, resolve as resolvePath } from 'node:path';
import { fileURLToPath } from 'node:url';
import { currentTenantFilter, tenantLabels } from '../src/agora/tenancy.js';
import { resolveAccessDeniedPage, } from '../src/dashboard/access_denied_page.js';
import { appCallerOf, MEDIA_OBJECTS_WRITE, viewerConsoleCapabilities, } from '../src/dashboard/console_apps.js';
import { resolveConsoleAuthorize, } from '../src/dashboard/console_authorize.js';
import { buildConsoleService, buildPartitionConsoleService, consoleDiskNames, readConsoleServiceConfig, } from '../src/dashboard/console_service.js';
import { resolveSignOut, resolveViewer } from '../src/dashboard/console_shell.js';
import { listVisibleConsoles, mediaConsoleSearch, otherConsoles, readAgoraConsoles, registerAgoraConsole, searchConsoles, } from '../src/dashboard/console_switcher.js';
import { isControlPlaneConsoleApp, } from '../src/dashboard/define_config.js';
import { registerMediaDevTools } from '../src/dashboard/dev_tools.js';
import { readCollectionsQuery, readObjectsQuery, readUploadsQuery, } from '../src/dashboard/list_api.js';
import { DashboardError } from '../src/dashboard/service.js';
import { contentTypeFor, normalizePath, renderIndexHtml } from '../src/dashboard/spa.js';
import { resolveConsoleTenantScope, } from '../src/dashboard/tenant_scope.js';
import { ACTOR_HEADER, buildFederatedMediaApp, FEDERATED_APP_KEY, FederatedAppError, FederatedConsoleService, federatedAppActions, sanitizeActor, validateFederatedConsoleApp, } from '../src/federation/console.js';
import { authkitClientOf, consoleSiblingsOf, consoleSideAuthMessage, ensureConsoleKey, hasKeyDirectory, resolveConsoleSideAuth, } from '../src/federation/console_auth.js';
import { CONSOLE_CRYPTO_KEY } from '../src/federation/redis_channel.js';
import { safeContentType } from '../src/http_safety.js';
import { MediaManager } from '../src/media_manager.js';
import { PARTITION_PATTERN } from '../src/topology/protocol.js';
/**
* Directory of the built SPA (`dist/spa`, copied in by `copy:stubs` — see `package.json` — from
* `@adonis-agora/media-dashboard`'s own build), relative to this compiled provider
* (`dist/providers`). Resolved lazily (not at module scope): `fileURLToPath` throws on any
* non-`file:` `import.meta.url`, which would make this provider unimportable under a test runner
* that doesn't use real file URLs.
*/
let spaDir;
function spaDirectory() {
spaDir ??= fileURLToPath(new URL('../assets/spa/', import.meta.url));
return spaDir;
}
/** This console's id in the app's `'agora.consoles'` registry. */
const CONSOLE_ID = 'media';
/** Content types a browser would run as a page (served by `object/raw` as a download). */
const ACTIVE_CONTENT = /^\s*(?:text\/html|application\/xhtml\+xml|image\/svg\+xml|(?:text|application)\/xml|[a-z]+\/[a-z0-9.+-]*\+xml|(?:text|application)\/(?:x-)?javascript|text\/ecmascript|application\/ecmascript|text\/xsl|multipart\/x-mixed-replace)\b/i;
/** Logged once at boot when `authorize` is omitted. Same wording in every Agora console. */
const NO_AUTHORIZE_WARNING = '[@adonis-agora/media] console has no `authorize` configured: it is open outside production and denies every request in production. Set `authorize` in config/media_dashboard.ts.';
/**
* Mounts the media-management console INTO `@adonis-agora/media` itself: a React SPA plus a JSON
* API, both under a configurable path and an optional host auth guard. The API delegates to the
* already-bound {@link MediaManager} singleton (bound by this same package's `MediaProvider`) via a
* pure {@link DashboardService} — disk `list`/`stat`/`copy`/`move`/`deleteMany` and the resumable
* session store. Nothing about storage is reimplemented here.
*
* Registering this provider is all a consuming app needs to do to get the dashboard — no separate
* `@adonis-agora/media-dashboard` install:
* ```ts
* providers: [
* () => import('@adonis-agora/media/media_provider'),
* () => import('@adonis-agora/media/dashboard_provider'),
* ]
* ```
*
* Route registration is deferred to `app.booted(...)` — same reason `MediaProvider#boot()` defers
* (see its long comment): the router service isn't safely resolvable synchronously inside a
* provider's own `boot()`.
*/
export default class MediaDashboardProvider {
app;
constructor(app) {
this.app = app;
}
/** Each request's `authorize` verdict, read again for the console's tenant scope. */
#decisions = new WeakMap();
/** Each request's console tenant scope (tenancy on). */
#scopes = new WeakMap();
/** The configured other apps (federated console), each built once on first use. */
#federated = new Map();
async boot() {
const config = this.app.config.get('media_dashboard', {});
if (config.enabled === false)
return;
const redisConnections = this.#redisConnections();
for (const [key, entry] of Object.entries(config.apps ?? {})) {
if (!FEDERATED_APP_KEY.test(key)) {
throw new Error(`[@adonis-agora/media] media_dashboard.apps: "${key}" is not a valid app key (1–64 characters of A-Z, a-z, 0-9, _ . -)`);
}
if (isControlPlaneConsoleApp(entry)) {
if (entry.actions !== undefined && typeof entry.actions !== 'boolean') {
throw new Error(`[@adonis-agora/media] media_dashboard.apps.${key}.actions must be a boolean`);
}
if (!PARTITION_PATTERN.test(key)) {
throw new Error(`[@adonis-agora/media] media_dashboard.apps.${key}: not a valid app name`);
}
continue;
}
validateFederatedConsoleApp(key, entry, redisConnections, {
keyDirectory: hasKeyDirectory(await authkitClientOf(this.app.container)),
});
}
const controlPlaneApps = Object.values(config.apps ?? {}).some(isControlPlaneConsoleApp);
if (controlPlaneApps &&
this.app.config.get('media', undefined)?.topology !==
'control-plane') {
this.#warn("[@adonis-agora/media] media_dashboard.apps lists control-plane apps, but config/media.ts is not topology: 'control-plane': they will show no media");
}
// The access check, resolved once: the console's routes, its dev tools and the switcher share
// it. Each verdict is remembered for the request, for the console's tenant scope.
const resolved = this.#resolveAuthorize(config);
const gate = async (ctx) => {
const decision = resolved ? await resolved(ctx) : { allowed: true };
this.#decisions.set(ctx, decision);
return decision;
};
const decide = resolved ? gate : null;
// Developer tools on the app's dev MCP endpoint, when `@adonis-agora/agent/mcp_provider` bound
// its hub (its `register()` ran before any `boot()`). Gated by this console's own `authorize`.
await this.#registerDevTools(config, gate);
// The console switcher: this console joins the app's `'agora.consoles'` registry so the other
// Agora consoles can link to it (and search it), and it can link to them.
await this.#registerConsole(config, gate);
await this.app.booted(async () => {
// How this console signs its commands to each other app; a misconfigured one fails the boot.
await this.#checkFederatedAuth(config);
// Said once per process, when the routes mount.
if (!config.authorize)
this.#warn(NO_AUTHORIZE_WARNING);
const router = await this.app.container.make('router');
this.#registerRoutes(router, config, decide);
});
}
/**
* Resolve, once at boot, how this console authenticates its commands to each other app, and log
* it. An app it cannot authenticate to fails the boot when this console may run actions there;
* a browse-only entry (`actions: false`) only warns. Web processes only (ace commands never start
* a channel).
*/
async #checkFederatedAuth(config) {
const entries = Object.entries(config.apps ?? {}).filter((entry) => !isControlPlaneConsoleApp(entry[1]));
if (entries.length === 0)
return;
const environment = this.app.getEnvironment?.();
if (environment !== undefined && environment !== 'web')
return;
const siblings = await consoleSiblingsOf(this.app.container);
for (const [key, entry] of entries) {
const { mode, autoPartition } = resolveConsoleSideAuth({
plane: entry.controlPlane,
partition: entry.partition ?? key,
siblings,
});
if (mode) {
this.#info(`[@adonis-agora/media] console commands to "${key}": ${mode}`);
// Crypto embedded here: the app's key is created now, not on the first command (the app
// would warn that it is missing until someone opens this console).
const runtime = siblings.crypto;
if (autoPartition !== undefined && runtime?.service) {
await ensureConsoleKey(runtime, autoPartition).then((result) => {
if (result === 'created') {
this.#info(`[@adonis-agora/media] console commands: created the crypto key "${CONSOLE_CRYPTO_KEY}" in partition ${autoPartition}`);
}
}, (error) => this.#warn(error instanceof Error ? error.message : String(error)));
}
continue;
}
const message = consoleSideAuthMessage(key, siblings, entry.controlPlane);
// Entries may act by default (`actions: false` = browse only), as the doctor reports.
if (federatedAppActions(entry))
throw new Error(message);
this.#warn(message);
}
}
/**
* The console's service, built per request from the bound {@link MediaManager}. With tenancy on
* and a request at hand, it is confined to the tenants this viewer may see (see
* {@link #consoleScope}); without a request (no viewer), it sees nothing of a tenant.
*/
#service(config) {
const settings = this.#serviceConfig(config);
return async (ctx) => {
const manager = await this.app.container.make(MediaManager);
if (!manager.tenancy?.enabled)
return buildConsoleService(manager, settings);
const ids = ctx ? (await this.#consoleScope(ctx))?.ids : [];
return buildConsoleService(manager, settings, ids);
};
}
/**
* The service an API route runs on: another app's (`?app=<key>`, federated console) or this
* app's. A key that is not configured, or that `authorize`'s `apps` grant does not name, is a 404.
*/
#routeService(config, apiBase) {
const local = this.#service(config);
return async (ctx) => {
const picked = this.#selectedApp(config, ctx);
if (picked === undefined)
return local(ctx);
if (picked === null)
throw new DashboardError('unknown app', 404);
const spec = config.apps?.[picked];
if (isControlPlaneConsoleApp(spec)) {
const manager = await this.app.container.make(MediaManager);
return buildPartitionConsoleService(manager, this.#serviceConfig(config), picked, spec.actions ?? config.actions ?? false);
}
const app = await this.#federatedApp(config, picked);
const viewer = await resolveViewer(ctx, config.viewer).catch(() => null);
const decision = this.#decisions.get(ctx);
// Narrowed to media's console set; `access: 'read'` keeps no write. All of it when unsaid.
const capabilities = viewerConsoleCapabilities(decision?.allowed ? decision : undefined);
return new FederatedConsoleService(app, {
actions: spec ? federatedAppActions(spec) : false,
actor: viewer?.email ?? viewer?.label ?? 'anonymous',
// What `authorize` says this viewer may do (every console capability when it does not say).
...(capabilities !== undefined ? { capabilities } : {}),
rawUrl: (disk, key) => `${apiBase}/object/raw?${new URLSearchParams({ app: picked, disk, key }).toString()}`,
});
};
}
/**
* The other app this request is about (`?app=`): its key, `undefined` for this app, or `null` for
* a key that is not configured or not granted.
*/
#selectedApp(config, ctx) {
// Without `apps` the console is this app's only; `?app=` is not even read.
if (!config.apps || Object.keys(config.apps).length === 0)
return undefined;
const picked = ctx.request.qs().app;
if (typeof picked !== 'string' || picked === '')
return undefined;
if (!Object.hasOwn(config.apps ?? {}, picked))
return null;
const granted = this.#grantedApps(ctx);
return granted === undefined || granted.includes(picked) ? picked : null;
}
/**
* Whether this request's viewer may change media, on this app as on the others: what its
* `authorize` answered (`capabilities`, `access: 'read'`), or yes when it said nothing.
*/
#viewerMayWrite(ctx) {
const decision = this.#decisions.get(ctx);
return viewerConsoleCapabilities(decision?.allowed ? decision : undefined).includes(MEDIA_OBJECTS_WRITE);
}
/** Refuse a change this viewer may not make (`403`, the same words as the federated apps). */
#assertViewerMayWrite(ctx) {
if (!this.#viewerMayWrite(ctx)) {
throw new DashboardError(`the viewer lacks ${MEDIA_OBJECTS_WRITE}`, 403);
}
}
/** The apps `authorize` granted this request (`undefined`: all of them). */
#grantedApps(ctx) {
const decision = this.#decisions.get(ctx);
const apps = decision?.allowed ? decision.apps : undefined;
return apps === undefined || apps === '*' ? undefined : apps;
}
/** The app selector: this app, then the configured apps this viewer may see. */
#appPicker(config, ctx) {
const granted = this.#grantedApps(ctx);
const mayWrite = this.#viewerMayWrite(ctx);
const apps = Object.entries(config.apps ?? {})
.filter(([id]) => granted === undefined || granted.includes(id))
.map(([id, app]) => isControlPlaneConsoleApp(app)
? {
id,
label: app.label ?? id,
// Its data lives here, and this server runs the actions.
mode: 'control-plane',
actions: mayWrite && (app.actions ?? config.actions ?? false)
? 'here'
: 'none',
}
: {
id,
label: app.label ?? id,
mode: 'federated',
// Who runs actions on that app's media from here: the app itself, or nobody.
actions: mayWrite && federatedAppActions(app) ? 'app' : 'none',
});
return {
local: { label: config.appLabel ?? 'This app' },
apps,
selected: this.#selectedApp(config, ctx) ?? null,
};
}
/** The connection names of `config/redis.ts`, or `undefined` without one. */
#redisConnections() {
const redis = this.app.config.get('redis', undefined);
if (!redis || typeof redis !== 'object' || !redis.connections)
return undefined;
return {
names: Object.keys(redis.connections),
default: typeof redis.connection === 'string' ? redis.connection : undefined,
};
}
/** The configured app `id`, built (its stores and channel) on first use. */
#federatedApp(config, id) {
let app = this.#federated.get(id);
if (!app) {
const spec = config.apps?.[id];
if (!spec || isControlPlaneConsoleApp(spec)) {
return Promise.reject(new DashboardError('unknown app', 404));
}
app = buildFederatedMediaApp(id, spec, this.app).catch((error) => {
// A console-side failure to reach the app (its connection, its store): a 503 naming the
// app, the cause in this app's log.
throw new FederatedAppError(`${spec.label ?? id}: the console could not reach this app`, 503, error instanceof Error ? error.message : String(error));
});
// A failed build (a bad connection name) is retried on the next request, not cached.
app.catch(() => this.#federated.delete(id));
this.#federated.set(id, app);
}
return app;
}
async shutdown() {
const apps = [...this.#federated.values()];
this.#federated.clear();
await Promise.all(apps.map((app) => app.then((a) => a.close()).catch(() => undefined)));
}
/** The config the console's service is built from (this console's own, over the app's). */
#serviceConfig(config) {
return { ...readConsoleServiceConfig(this.app.config), console: config };
}
/**
* The tenants this viewer may see in the console, once per request, or `undefined` with tenancy
* off. `authorize` may grant `tenants` (`'*'` or a list); otherwise it is the viewer's own active
* tenant. A `?tenant=` pick outside the grant is answered with nothing and logged.
*/
#consoleScope(ctx) {
let scope = this.#scopes.get(ctx);
if (!scope) {
scope = this.#resolveConsoleScope(ctx);
this.#scopes.set(ctx, scope);
}
return scope;
}
async #resolveConsoleScope(ctx) {
const manager = await this.app.container.make(MediaManager);
if (!manager.tenancy?.enabled)
return undefined;
const decision = this.#decisions.get(ctx);
const granted = decision?.allowed ? decision.tenants : undefined;
let own;
try {
const filter = currentTenantFilter(manager.tenancy);
if (filter.mode === 'tenant') {
own = { id: filter.tenant.id, kind: filter.tenant.kind, slug: filter.tenant.slug };
}
}
catch {
// `tenancy.required` throws without a tenant: in the console that is just "no organization".
own = undefined;
}
const picked = ctx.request.qs().tenant;
const scope = resolveConsoleTenantScope({
granted,
own,
selected: typeof picked === 'string' ? picked : undefined,
});
if (scope.forged) {
this.#warn(`[@adonis-agora/media] console: organization "${scope.selected ?? ''}" requested outside the viewer's scope (${ctx.request.url(false)}); answered with nothing`);
}
return scope;
}
/** The console's "Organization" control: `off`, `none`, `fixed` (one) or `pick` (several). */
async #tenantPicker(config, ctx) {
// Another app's media (federated console): that app's organizations are not this app's.
// Gated like the routes (`#selectedApp`): without `apps`, `?app=` is not read at all.
if (this.#selectedApp(config, ctx) !== undefined) {
return { mode: 'off', all: false, selected: null, tenants: [] };
}
const scope = await this.#consoleScope(ctx);
if (!scope)
return { mode: 'off', all: false, selected: null, tenants: [] };
if (scope.authorized === 'none')
return { mode: 'none', all: false, selected: null, tenants: [] };
let ids;
if (scope.authorized === '*') {
const manager = await this.app.container.make(MediaManager);
ids = (await manager.store.listTenants?.()) ?? [];
}
else {
ids = [...scope.authorized];
}
const labels = await tenantLabels(ids, scope.own?.kind);
if (scope.own?.slug)
labels[scope.own.id] = scope.own.slug;
const tenants = ids.map((id) => ({ id, label: labels[id] ?? id }));
const mode = scope.authorized !== '*' && tenants.length === 1 ? 'fixed' : 'pick';
return { mode, all: scope.authorized === '*', selected: scope.selected ?? null, tenants };
}
async #registerDevTools(config, decide) {
const service = this.#service(config);
// An auxiliary feature: a hub that throws must not take the app's boot down with it.
try {
await registerMediaDevTools(this.app.container, {
// The dev tools' decision shape: a redirect is an unauthenticated refusal there.
authorize: async (ctx) => {
const decision = await decide(ctx);
if (decision.allowed)
return { allowed: true };
if (decision.status === 302) {
return { allowed: false, reason: 'unauthenticated', redirectTo: decision.redirectTo };
}
return { allowed: false, reason: decision.reason };
},
service: (ctx) => service(ctx),
actions: config.actions ?? false,
});
}
catch (error) {
this.#warn(`[@adonis-agora/media] could not register the developer tools: ${error instanceof Error ? error.message : String(error)}`);
}
}
async #registerConsole(config, decide) {
const basePath = normalizePath(config.basePath ?? '/media/dashboard');
const service = this.#service(config);
const diskNames = this.#resolveDiskNames(config);
try {
await registerAgoraConsole(this.app.container, {
id: CONSOLE_ID,
title: 'Media',
package: '@adonis-agora/media',
icon: 'media',
path: basePath,
order: 50,
authorize: decide,
search: mediaConsoleSearch(async (ctx) => {
const svc = await service(ctx);
return {
find: async (id) => {
const entry = await svc.mediaEntry(id).catch(() => null);
return entry
? { id: entry.id, collection: entry.collection, fileName: entry.fileName }
: null;
},
collections: async () => (await svc.collectionsSummary()).data,
disks: () => diskNames,
};
}, basePath),
}, { warn: (message) => this.#warn(message) });
}
catch (error) {
this.#warn(`[@adonis-agora/media] could not join the console switcher: ${error instanceof Error ? error.message : String(error)}`);
}
}
#registerRoutes(router, config, decide) {
const basePath = normalizePath(config.basePath ?? '/media/dashboard');
const apiBase = normalizePath(config.apiBasePath ?? `${basePath}/api`);
const uploadsBase = normalizePath(config.uploadsPrefix ?? '/media/uploads');
const tusBase = normalizePath(config.tusPrefix ?? '/media/uploads/tus');
const actions = config.actions ?? false;
const middleware = config.middleware
? Array.isArray(config.middleware)
? config.middleware
: [config.middleware]
: [];
// Access check — the `ConsoleAuthorize` contract shared by every @adonis-agora console. Runs
// BEFORE `middleware` (both must pass). Sign-in is the app's own: the console has no login.
// Omitted: open outside production, every page/API request refused (`403`) in production.
// A denied request honors an answer the check wrote itself (a `location` header or a queued
// body); `{ redirectTo }` is a `302` for a page navigation and a `401` for the API; otherwise
// `401` for `reason: 'unauthenticated'` and `403` for everything else (fail closed) —
// `{ error: 'unauthenticated' | 'forbidden' }` JSON for the API, the access-denied page (or the
// host's `accessDenied`) for a page.
const authorizeGate = (mode) => decide
? [
async (ctx, next) => {
const decision = await decide(ctx);
if (decision.allowed)
return next();
// An answer the check wrote stands on its own — the handler must NOT run after it
// (it would queue a JSON body onto a 302).
if (responseAnswered(ctx))
return;
if (decision.status === 302) {
// A sign-in redirect: followed by a page navigation, a `401` naming it for the API.
if (mode === 'api') {
ctx.response
.status(401)
.send({ error: 'unauthenticated', redirectTo: decision.redirectTo });
}
else {
ctx.response.redirect(decision.redirectTo);
}
return;
}
if (mode === 'api') {
ctx.response.status(decision.status).send({ error: decision.reason });
return;
}
await denyPage(ctx, {
basePath,
accessDenied: config.accessDenied,
status: decision.status,
reason: decision.reason,
});
},
]
: [];
const service = this.#routeService(config, apiBase);
this.#mountApi(router, apiBase, config, service, [...authorizeGate('api'), ...middleware]);
this.#mountSpa(router, basePath, config, { apiBase, uploadsBase, tusBase, actions }, [
...authorizeGate('page'),
...middleware,
]);
}
/**
* The per-request access check, or `null` for none. Without `authorize` the console is open
* outside production and refuses every page/API request in production (and says so once, when its
* routes mount).
*/
#resolveAuthorize(config) {
if (config.authorize)
return resolveConsoleAuthorize(config.authorize);
if (this.app.inProduction !== true)
return null;
return async () => ({ allowed: false, status: 403, reason: 'forbidden' });
}
/** An `info` line through the app logger when one is bound. Never throws. */
#info(message) {
void Promise.resolve()
.then(() => this.app.container.make('logger'))
.then((logger) => {
const info = logger?.info;
if (typeof info === 'function')
info.call(logger, message);
})
.catch(() => { });
}
/**
* An action another app's federated console sent here (`proxyActions`, an app caller): logged with
* the app and the viewer it names, like the actions that come over Redis.
*/
#logCallerAction(ctx) {
const caller = appCallerOf(ctx);
if (!caller)
return;
const actor = sanitizeActor(ctx.request.header(ACTOR_HEADER)) ?? 'unknown';
this.#info(`[@adonis-agora/media] federated console: ${ctx.request.url(false)} by ${actor} from app ${sanitizeActor(caller.app) ?? 'unknown'}`);
}
/** Warn through the app logger when one is bound, else the console. Never throws. */
#warn(message) {
void Promise.resolve()
.then(() => this.app.container.make('logger'))
.then((logger) => {
const warn = logger?.warn;
if (typeof warn === 'function')
warn.call(logger, message);
else
console.warn(message);
})
.catch(() => console.warn(message));
}
#mountApi(router, apiBase, config, service, middleware) {
const fail = (ctx, error) => {
const status = error instanceof DashboardError ? error.status : 500;
const message = error instanceof Error ? error.message : 'dashboard error';
// The owning app's own message stays in this app's log (a 502 does not show it).
if (error instanceof FederatedAppError && error.detail !== undefined) {
this.#warn(`[@adonis-agora/media] federated console: ${message}: ${error.detail}`);
}
return ctx.response.status(status).json({ error: message });
};
const json = (handler, okStatus = 200) => {
return async (ctx) => {
try {
const result = await handler(await service(ctx), ctx);
if (result === undefined)
return ctx.response.status(204).send('');
return ctx.response.status(okStatus).json(result);
}
catch (error) {
return fail(ctx, error);
}
};
};
// An action: logged when another app's console sent it (an app caller, `proxyActions`).
const action = (handler) => json(async (svc, ctx) => {
// The viewer's capabilities apply here too, on this app as on the others.
this.#assertViewerMayWrite(ctx);
this.#logCallerAction(ctx);
await handler(svc, ctx);
});
const group = router.group(() => {
router
.get('/topology', json(async (svc, ctx) => {
const topology = await svc.topology();
// The UI disables what this viewer may not do.
return { ...topology, actions: topology.actions && this.#viewerMayWrite(ctx) };
}))
.as('media.dashboard.topology');
// Organizations (tenancy): the picker's data, and the audited switch.
router
.get('/tenants', async (ctx) => {
ctx.response.header('cache-control', 'private, no-store');
return ctx.response.status(200).json(await this.#tenantPicker(config, ctx));
})
.as('media.dashboard.tenants');
router
.post('/tenants/:id/select', async (ctx) => {
const id = String(ctx.params.id);
const picker = await this.#tenantPicker(config, ctx);
const allowed = picker.mode !== 'off' &&
picker.mode !== 'none' &&
(id === '*' ? picker.all : picker.tenants.some((t) => t.id === id));
this.#info(`[@adonis-agora/media] console: organization switch to "${id}" ${allowed ? 'allowed' : 'refused'}`);
return ctx.response
.status(allowed ? 200 : 404)
.json(allowed ? { tenant: id } : { error: 'not found' });
})
.as('media.dashboard.tenants.select');
// The federated console's app selector: this app, then the other apps this viewer may see.
router
.get('/apps', async (ctx) => {
ctx.response.header('cache-control', 'private, no-store');
return ctx.response.status(200).json(this.#appPicker(config, ctx));
})
.as('media.dashboard.apps');
// The console switcher: the other Agora consoles this viewer may open, and a search across them.
router
.get('/consoles', async (ctx) => {
const registry = await readAgoraConsoles(this.app.container);
ctx.response.header('cache-control', 'private, no-store');
return ctx.response
.status(200)
.json(await listVisibleConsoles(registry, CONSOLE_ID, ctx));
})
.as('media.dashboard.consoles');
router
.get('/consoles/search', async (ctx) => {
const registry = await readAgoraConsoles(this.app.container);
const q = ctx.request.qs().q;
ctx.response.header('cache-control', 'private, no-store');
return ctx.response
.status(200)
.json(await searchConsoles(registry, CONSOLE_ID, ctx, typeof q === 'string' ? q : ''));
})
.as('media.dashboard.consoles.search');
router
.get('/disks', json(async (svc) => svc.disks()))
.as('media.dashboard.disks');
router
.get('/objects', json(async (svc, ctx) => {
const { disk, params } = await readObjectsQuery(ctx);
return svc.objects(disk, params);
}))
.as('media.dashboard.objects');
router
.get('/object', json(async (svc, ctx) => {
const disk = str(ctx, 'disk');
const key = str(ctx, 'key');
if (!disk)
throw new DashboardError('disk is required', 400);
return svc.object(disk, key ?? '');
}))
.as('media.dashboard.object');
router
.post('/object', async (ctx) => {
// Raw bytes as `application/octet-stream` so the host's JSON/urlencoded body parsers never
// consume the stream; `ctx.request.request` is still the untouched Node request stream for
// any content type the app's bodyparser wasn't configured to parse. The real MIME rides as
// the `type` query param and becomes the stored object's Content-Type.
try {
const disk = str(ctx, 'disk');
const key = str(ctx, 'key');
const type = str(ctx, 'type');
if (!disk)
throw new DashboardError('disk is required', 400);
if (!key)
throw new DashboardError('key is required', 400);
this.#assertViewerMayWrite(ctx);
await (await service(ctx)).putObject(disk, key, ctx.request.request, type);
return ctx.response.status(204).send('');
}
catch (error) {
return fail(ctx, error);
}
})
.as('media.dashboard.object.upload');
router
.get('/object/raw', async (ctx) => {
try {
const disk = str(ctx, 'disk');
const key = str(ctx, 'key');
if (!disk)
throw new DashboardError('disk is required', 400);
const svc = await service(ctx);
// Another app's bytes pass through here only with its `proxyObjects`; otherwise the
// browser goes to that app's URL.
if (svc instanceof FederatedConsoleService && !svc.servesBytes) {
return ctx.response.redirect(await svc.objectRedirect(disk, key ?? ''));
}
const streamed = await svc.objectStream(disk, key ?? '');
const { stream, size } = streamed;
// A disk's or another app's type may be anything: never a header Node refuses.
const contentType = safeContentType(streamed.contentType);
ctx.response.header('content-type', contentType);
ctx.response.header('x-content-type-options', 'nosniff');
// Uploaded HTML/SVG/XML/script must never run as a page of this origin: downloaded,
// and sandboxed if opened anyway. Everything else (images, PDF, video) shows inline.
if (ACTIVE_CONTENT.test(contentType)) {
ctx.response.header('content-disposition', 'attachment');
ctx.response.header('content-security-policy', "default-src 'none'; sandbox");
}
else {
ctx.response.header('content-disposition', 'inline');
}
if (Number.isFinite(size))
ctx.response.header('content-length', String(size));
return ctx.response.stream(stream);
}
catch (error) {
return fail(ctx, error);
}
})
.as('media.dashboard.object.raw');
router
.get('/object/insights', json(async (svc, ctx) => {
const disk = str(ctx, 'disk');
const key = str(ctx, 'key');
if (!disk)
throw new DashboardError('disk is required', 400);
return svc.objectInsights(disk, key ?? '');
}))
.as('media.dashboard.object.insights');
router
.get('/uploads', json(async (svc, ctx) => svc.uploads(await readUploadsQuery(ctx))))
.as('media.dashboard.uploads');
router
.get('/uploads/:id', json(async (svc, ctx) => svc.uploadDetail(String(ctx.params.id))))
.as('media.dashboard.uploads.show');
router
.post('/uploads/:id/abort', action(async (svc, ctx) => {
await svc.abortUpload(String(ctx.params.id));
}))
.as('media.dashboard.uploads.abort');
router
.get('/collections', json(async (svc, ctx) => svc.collections(await readCollectionsQuery(ctx))))
.as('media.dashboard.collections');
router
.get('/collections/summary', json(async (svc) => svc.collectionsSummary()))
.as('media.dashboard.collections.summary');
router
.get('/media-record', json(async (svc, ctx) => {
const id = str(ctx, 'id');
if (!id)
throw new DashboardError('id is required', 400);
return svc.mediaRecord(id);
}))
.as('media.dashboard.media_record');
router
.post('/media-record/delete', action(async (svc, ctx) => {
const body = ctx.request.body();
if (!body.id)
throw new DashboardError('id is required', 400);
await svc.deleteMediaRecord(body.id);
}))
.as('media.dashboard.media_record.delete');
router
.post('/copy', action(async (svc, ctx) => {
await svc.copy(copyMoveBody(ctx));
}))
.as('media.dashboard.copy');
router
.post('/move', action(async (svc, ctx) => {
await svc.move(copyMoveBody(ctx));
}))
.as('media.dashboard.move');
router
.post('/delete', action(async (svc, ctx) => {
const body = ctx.request.body();
if (!body.disk)
throw new DashboardError('disk is required', 400);
await svc.remove({
disk: body.disk,
keys: Array.isArray(body.keys) ? body.keys : [],
});
}))
.as('media.dashboard.delete');
router
.post('/folder', action(async (svc, ctx) => {
await svc.createFolder(folderBody(ctx));
}))
.as('media.dashboard.folder.create');
router
.post('/folder/delete', action(async (svc, ctx) => {
await svc.deleteFolder(folderBody(ctx));
}))
.as('media.dashboard.folder.delete');
router
.post('/folder/copy', action(async (svc, ctx) => {
await svc.copyFolder(copyMoveBody(ctx));
}))
.as('media.dashboard.folder.copy');
router
.post('/folder/move', action(async (svc, ctx) => {
await svc.moveFolder(copyMoveBody(ctx));
}))
.as('media.dashboard.folder.move');
});
group.prefix(apiBase);
// `authorize`, then host `middleware`. The mutating routes above are further gated at the service
// layer by `actions` (unconditionally mounted; `DashboardService` 403s when disabled), so
// read-only hosts can leave them mounted without enabling `actions`.
applyMiddleware(group, middleware);
}
#mountSpa(router, basePath, config, bootstrap, middleware) {
const serveIndex = async (ctx) => {
let html;
try {
html = await readFile(resolvePath(spaDirectory(), 'index.html'), 'utf8');
}
catch {
return ctx.response
.status(404)
.send('media dashboard SPA is not built (run the package build to emit dist/assets/spa)');
}
// The console shell's fields: the switcher, ⌘K search (whenever a console registry exists —
// this console registers its own search), the signed-in viewer and the sign-out (the host's
// option, else the one an account console announced on the registry).
const registry = await readAgoraConsoles(this.app.container);
const viewer = await resolveViewer(ctx, config.viewer);
const signOut = resolveSignOut(ctx, config.signOut, registry);
return ctx.response
.header('content-type', 'text/html; charset=utf-8')
.header('cache-control', 'no-store, must-revalidate')
.send(renderIndexHtml(html, basePath, {
...bootstrap,
switcher: {
endpoint: `${bootstrap.apiBase}/consoles`,
others: otherConsoles(registry, CONSOLE_ID),
},
...(registry ? { search: { endpoint: `${bootstrap.apiBase}/consoles/search` } } : {}),
...(viewer ? { viewer } : {}),
...(signOut ? { signOut } : {}),
}));
};
const group = router.group(() => {
router.get('/', serveIndex).as('media.dashboard.index');
router
.get('/assets/:file', async (ctx) => {
const file = basename(String(ctx.params.file));
const root = resolvePath(spaDirectory(), 'assets');
const assetPath = resolvePath(root, file);
if (!assetPath.startsWith(root))
return ctx.response.status(404).send('');
let bytes;
try {
bytes = await readFile(assetPath);
}
catch {
return ctx.response.status(404).send('');
}
return ctx.response
.header('content-type', contentTypeFor(file))
.header('cache-control', 'public, max-age=31536000, immutable')
.send(bytes);
})
.as('media.dashboard.assets');
});
group.prefix(basePath);
applyMiddleware(group, middleware);
}
/** Derive browsable disk names from the media config when the console config does not list them. */
#resolveDiskNames(config) {
return consoleDiskNames(this.#serviceConfig(config));
}
}
function str(ctx, key) {
const value = ctx.request.input(key);
return typeof value === 'string' && value !== '' ? value : undefined;
}
function copyMoveBody(ctx) {
const body = ctx.request.body();
if (!body.disk)
throw new DashboardError('disk is required', 400);
return {
disk: body.disk,
from: body.from ?? '',
to: body.to ?? '',
...(body.toDisk !== undefined ? { toDisk: body.toDisk } : {}),
};
}
/** Body for the folder create/delete actions — a disk and the folder prefix. */
function folderBody(ctx) {
const body = ctx.request.body();
if (!body.disk)
throw new DashboardError('disk is required', 400);
return { disk: body.disk, prefix: body.prefix ?? '' };
}
/** Apply host middleware to a route group without depending on Adonis's exact middleware typings. */
function applyMiddleware(group, middleware) {
if (middleware.length === 0)
return;
group.use(middleware);
}
/* Access-denied page -------------------------------------------------------------------------- */
/**
* Answer a refused PAGE navigation with HTML instead of the API's JSON: the built-in page, the
* host's tweaked version of it, or whatever the host's `accessDenied` renderer produced. Stands down
* when the request is already answered — an `authorize` hook (or the renderer) that wrote a redirect
* keeps it; the provider never overwrites a `location` header. Same status as the API's JSON: `401`
* (`unauthenticated` — the page offers a "Sign in" button when `accessDenied.loginHref` points at
* the host's login) or `403` (`forbidden` — the hook knew who was asking and said no).
*/
async function denyPage(ctx, options) {
const answered = () => responseAnswered(ctx);
if (answered())
return;
const nonce = cspNonce(ctx);
const info = {
status: options.status,
reason: options.reason,
basePath: options.basePath,
...(nonce !== undefined ? { nonce } : {}),
};
const html = await resolveAccessDeniedPage(info, options.accessDenied, ctx, answered);
if (html === null)
return;
ctx.response
.status(info.status)
.header('content-type', 'text/html; charset=utf-8')
.header('cache-control', 'no-store, must-revalidate')
.send(html);
}
/**
* Whether something already answered this request: a redirect (`location` header — the signal the
* `authorize` contract has always honoured) or a body queued on the response. The body check reads
* AdonisJS's `response.hasLazyBody` structurally so a plain-object `ctx` double in a unit test
* (which has neither) still works.
*/
function responseAnswered(ctx) {
if (ctx.response.getHeader('location'))
return true;
const response = ctx.response;
return response.hasLazyBody === true || response.headersSent === true;
}
/**
* The request's CSP nonce when the host runs `@adonisjs/shield` with `@nonce` in its policy (shield
* exposes it as `response.nonce`). Read structurally: this package neither depends on shield nor
* cares which middleware minted the nonce — only that the page's inline `<style>` carries it.
*/
function cspNonce(ctx) {
const nonce = ctx.response.nonce;
return typeof nonce === 'string' && nonce !== '' ? nonce : undefined;
}
//# sourceMappingURL=dashboard_provider.js.map