@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
706 lines • 34.5 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 { resolveConsoleAuthorize, } from '../src/dashboard/console_authorize.js';
import { listVisibleConsoles, mediaConsoleSearch, otherConsoles, readAgoraConsoles, registerAgoraConsole, searchConsoles, } from '../src/dashboard/console_switcher.js';
import { registerMediaDevTools } from '../src/dashboard/dev_tools.js';
import { DashboardError, DashboardService } from '../src/dashboard/service.js';
import { contentTypeFor, normalizePath, renderIndexHtml } from '../src/dashboard/spa.js';
import { consoleKeyPrefixes, resolveConsoleTenantScope, scopedManager, } from '../src/dashboard/tenant_scope.js';
import { MediaManager } from '../src/media_manager.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';
/** 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();
async boot() {
const config = this.app.config.get('media_dashboard', {});
if (config.enabled === false)
return;
// 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 () => {
// 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);
});
}
/**
* 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 basePath = normalizePath(config.basePath ?? '/media/dashboard');
const apiBase = normalizePath(config.apiBasePath ?? `${basePath}/api`);
const diskNames = this.#resolveDiskNames(config);
const objectUrls = { strategy: this.#resolveObjectUrlStrategy(config), apiBasePath: apiBase };
return async (ctx) => {
const manager = await this.app.container.make(MediaManager);
const options = { diskNames, actions: config.actions ?? false, objectUrls };
if (!manager.tenancy?.enabled) {
// Strategy and mount path travel together: a strategy without the path it needs would be
// a half-configured state that builds `/object/raw` URLs rooted at nothing.
return new DashboardService(manager, options, config.objectInsights ?? []);
}
const ids = ctx ? (await this.#consoleScope(ctx))?.ids : [];
const keyPrefixes = consoleKeyPrefixes(ids);
return new DashboardService(scopedManager(manager, ids), { ...options, ...(keyPrefixes !== undefined ? { keyPrefixes } : {}) }, config.objectInsights ?? []);
};
}
/**
* 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(ctx) {
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, {
authorize: decide,
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()).collections,
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 (mode === 'api') {
ctx.response.status(decision.status).send({
error: decision.reason,
...('redirectTo' in decision ? { redirectTo: decision.redirectTo } : {}),
});
return;
}
if ('redirectTo' in decision) {
ctx.response.redirect(decision.redirectTo);
return;
}
await denyPage(ctx, {
basePath,
accessDenied: config.accessDenied,
status: decision.status,
reason: decision.reason,
});
},
]
: [];
const service = this.#service(config);
this.#mountApi(router, apiBase, service, [...authorizeGate('api'), ...middleware]);
this.#mountSpa(router, basePath, { 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(() => { });
}
/** 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, service, middleware) {
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) {
const status = error instanceof DashboardError ? error.status : 500;
const message = error instanceof Error ? error.message : 'dashboard error';
return ctx.response.status(status).json({ error: message });
}
};
};
const group = router.group(() => {
router
.get('/topology', json(async (svc) => svc.topology()))
.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(ctx));
})
.as('media.dashboard.tenants');
router
.post('/tenants/:id/select', async (ctx) => {
const id = String(ctx.params.id);
const picker = await this.#tenantPicker(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 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 = str(ctx, 'disk');
if (!disk)
throw new DashboardError('disk is required', 400);
const prefix = str(ctx, 'prefix');
// `?after=&first=` — the ecosystem's cursor pagination interface (mirrors
// `@adonis-agora/filter`'s `CursorParams`). Forward-only: no `before`/`last`.
const after = str(ctx, 'after');
const first = ctx.request.input('first');
return svc.objects(disk, {
...(prefix !== undefined ? { prefix } : {}),
...(after !== undefined ? { after } : {}),
...(first !== undefined ? { first: Number(first) } : {}),
});
}))
.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);
await (await service(ctx)).putObject(disk, key, ctx.request.request, type);
return ctx.response.status(204).send('');
}
catch (error) {
const status = error instanceof DashboardError ? error.status : 500;
const message = error instanceof Error ? error.message : 'dashboard error';
return ctx.response.status(status).json({ error: message });
}
})
.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 { stream, contentType, size } = await (await service(ctx)).objectStream(disk, key ?? '');
ctx.response.header('content-type', contentType);
ctx.response.header('content-disposition', 'inline');
if (Number.isFinite(size))
ctx.response.header('content-length', String(size));
return ctx.response.stream(stream);
}
catch (error) {
const status = error instanceof DashboardError ? error.status : 500;
const message = error instanceof Error ? error.message : 'dashboard error';
return ctx.response.status(status).json({ error: message });
}
})
.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) => {
const disk = str(ctx, 'disk');
const prefix = str(ctx, 'prefix');
return svc.uploads({
...(disk !== undefined ? { disk } : {}),
...(prefix !== undefined ? { prefix } : {}),
});
}))
.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', json(async (svc, ctx) => {
await svc.abortUpload(String(ctx.params.id));
}))
.as('media.dashboard.uploads.abort');
router
.get('/collections', json(async (svc, ctx) => {
const collection = str(ctx, 'collection');
const ownerType = str(ctx, 'ownerType');
const ownerId = str(ctx, 'ownerId');
const prefix = str(ctx, 'prefix');
// Same `?after=&first=` cursor interface as `/objects` — see that route.
const after = str(ctx, 'after');
const first = ctx.request.input('first');
return svc.collections({
...(collection !== undefined ? { collection } : {}),
...(ownerType !== undefined ? { ownerType } : {}),
...(ownerId !== undefined ? { ownerId } : {}),
...(prefix !== undefined ? { prefix } : {}),
...(after !== undefined ? { after } : {}),
...(first !== undefined ? { first: Number(first) } : {}),
});
}))
.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', json(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', json(async (svc, ctx) => {
await svc.copy(copyMoveBody(ctx));
}))
.as('media.dashboard.copy');
router
.post('/move', json(async (svc, ctx) => {
await svc.move(copyMoveBody(ctx));
}))
.as('media.dashboard.move');
router
.post('/delete', json(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', json(async (svc, ctx) => {
await svc.createFolder(folderBody(ctx));
}))
.as('media.dashboard.folder.create');
router
.post('/folder/delete', json(async (svc, ctx) => {
await svc.deleteFolder(folderBody(ctx));
}))
.as('media.dashboard.folder.delete');
router
.post('/folder/copy', json(async (svc, ctx) => {
await svc.copyFolder(copyMoveBody(ctx));
}))
.as('media.dashboard.folder.copy');
router
.post('/folder/move', json(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, 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)');
}
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(await readAgoraConsoles(this.app.container), CONSOLE_ID),
},
}));
};
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);
}
/**
* Which `url` the console reports for an object's bytes. An explicit `objectUrls` always wins;
* when unset, the console follows the core media config: a host already streaming every read
* through the app (`delivery.mode: 'proxy'`) has declared its store unreachable from a browser,
* so a signed URL minted for the internal endpoint would be a link the console cannot open.
* Anything else keeps the historical `'auto'`.
*/
#resolveObjectUrlStrategy(config) {
if (config.objectUrls)
return config.objectUrls;
const media = this.app.config.get('media', {});
return media.delivery?.mode === 'proxy' ? 'proxy' : 'auto';
}
/** Derive browsable disk names from the media config when the console config does not list them. */
#resolveDiskNames(config) {
if (config.disks && config.disks.length > 0)
return config.disks;
const media = this.app.config.get('media', {});
const drive = this.app.config.get('drive', {});
const defaultName = media.disk ?? drive.default ?? 'default';
const configured = media.disks ? Object.keys(media.disks) : [];
return Array.from(new Set([defaultName, ...configured]));
}
}
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