@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
149 lines • 5.86 kB
JavaScript
import { createHash, timingSafeEqual } from 'node:crypto';
function isAuthorizerClass(value) {
return (typeof value === 'function' &&
typeof value.prototype?.authorize === 'function');
}
function lazyModuleClass(value) {
if (typeof value !== 'object' || value === null || !('default' in value))
return undefined;
const candidate = value.default;
return isAuthorizerClass(candidate) ? candidate : undefined;
}
async function runClass(Class, ctx) {
const resolver = ctx
.containerResolver;
const instance = (resolver ? await resolver.make(Class) : new Class());
return instance.authorize(ctx);
}
const FORBIDDEN = { allowed: false, status: 403, reason: 'forbidden' };
/** Normalize an `authorize` answer. Anything that is not an explicit allow denies. */
export function normalizeConsoleAuthorizeResult(result) {
if (result === true)
return { allowed: true };
if (typeof result !== 'object' || result === null)
return FORBIDDEN;
const record = result;
if (record.allowed === true) {
if (record.tenants === '*')
return { allowed: true, tenants: '*' };
if (Array.isArray(record.tenants)) {
const tenants = record.tenants
.filter((t) => typeof t === 'string')
.map((t) => t.trim())
.filter((t) => t !== '');
return { allowed: true, tenants: [...new Set(tenants)] };
}
return { allowed: true };
}
if (typeof record.redirectTo === 'string' && record.redirectTo !== '') {
return {
allowed: false,
status: 401,
reason: 'unauthenticated',
redirectTo: record.redirectTo,
};
}
if (record.reason === 'unauthenticated') {
return { allowed: false, status: 401, reason: 'unauthenticated' };
}
return FORBIDDEN;
}
/**
* Turn a {@link ConsoleAuthorize} option into a check that runs per request. A class is built
* through `ctx.containerResolver`; a lazy import is loaded once and remembered. A throw denies.
*/
export function resolveConsoleAuthorize(authorize) {
let lazyClass;
return async (ctx) => {
try {
if (isAuthorizerClass(authorize)) {
return normalizeConsoleAuthorizeResult(await runClass(authorize, ctx));
}
if (lazyClass)
return normalizeConsoleAuthorizeResult(await runClass(lazyClass, ctx));
// An inline function and a lazy import look alike: call it and inspect the answer. A module
// whose `default` is an authorizer class was a lazy import; remember the class so the import
// runs only once.
const result = await authorize(ctx);
const loaded = lazyModuleClass(result);
if (loaded) {
lazyClass = loaded;
return normalizeConsoleAuthorizeResult(await runClass(loaded, ctx));
}
return normalizeConsoleAuthorizeResult(result);
}
catch {
return FORBIDDEN;
}
};
}
function digest(value) {
return createHash('sha256').update(value).digest();
}
/**
* An `authorize` check for machine access: allows a request whose `Authorization` header is
* `Bearer <token>`, and answers `{ allowed: false, reason: 'unauthenticated' }` (`401`) otherwise.
*
* ```ts
* authorize: authorizeByToken({ token: env.get('CONSOLE_TOKEN') }),
* ```
*
* Throws at config time when `token` is empty or undefined.
*/
export function authorizeByToken(options) {
const token = options?.token;
if (typeof token !== 'string' || token === '') {
throw new Error('authorizeByToken: `token` must be a non-empty string');
}
const expected = digest(token);
return (ctx) => {
const header = ctx.request.header('authorization');
const match = typeof header === 'string' ? /^Bearer\s+(.+)$/i.exec(header.trim()) : null;
if (match?.[1] && timingSafeEqual(digest(match[1]), expected))
return { allowed: true };
return { allowed: false, reason: 'unauthenticated' };
};
}
/**
* An `authorize` that allows a request when ANY of `authorizers` allows it, tried in order — e.g. a
* machine token for MCP clients OR a signed-in admin for the browser:
*
* ```ts
* authorize: anyAuthorize(
* authorizeByToken({ token: env.get('CONSOLE_TOKEN') }),
* (ctx) => ctx.auth.user?.isAdmin === true,
* ),
* ```
*
* When none allows: a redirect if one asked for it, `401` if any said "unauthenticated", `403`
* otherwise. A throwing authorizer counts as a `403` and the next one is still tried.
*/
export function anyAuthorize(...authorizers) {
if (authorizers.length === 0) {
throw new Error('anyAuthorize: pass at least one authorize');
}
const resolved = authorizers.map((authorize) => resolveConsoleAuthorize(authorize));
return async (ctx) => {
let unauthenticated = false;
let redirectTo;
for (const authorize of resolved) {
const decision = await authorize(ctx);
if (decision.allowed) {
return decision.tenants !== undefined
? { allowed: true, tenants: decision.tenants }
: { allowed: true };
}
if (decision.reason !== 'unauthenticated')
continue;
unauthenticated = true;
if ('redirectTo' in decision && redirectTo === undefined)
redirectTo = decision.redirectTo;
}
if (redirectTo !== undefined)
return { redirectTo };
if (unauthenticated)
return { allowed: false, reason: 'unauthenticated' };
return { allowed: false, reason: 'forbidden' };
};
}
//# sourceMappingURL=console_authorize.js.map