@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
128 lines • 5.23 kB
JavaScript
import { timingSafeEqual } from 'node:crypto';
function hasVerify(value) {
return (!!value &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.verify === 'function');
}
function isVerifierClass(value) {
return (typeof value === 'function' &&
typeof value.prototype?.verify === 'function');
}
/**
* Validates a verifier's answer. `null` refuses; `{ partition, capabilities }` accepts; anything else
* throws, so a malformed answer is never taken for an accepted tenant. Capabilities are not
* defaulted: a verifier must say what the token may do.
*/
export function checkVerifiedTenant(result) {
if (result === null || result === undefined)
return null;
const value = result;
if (typeof value === 'object' &&
typeof value.partition === 'string' &&
value.partition.length > 0 &&
Array.isArray(value.capabilities) &&
value.capabilities.every((capability) => typeof capability === 'string') &&
(value.clientId === undefined || typeof value.clientId === 'string')) {
return {
partition: value.partition,
capabilities: value.capabilities,
...(value.clientId !== undefined ? { clientId: value.clientId } : {}),
};
}
throw new TypeError('[@adonis-agora/media] verifyTenant must return { partition: string, capabilities: string[] } or null');
}
/** Turns any `verifyTenant` form into the function the control plane calls. */
export function resolveTenantVerifier(input) {
if (isVerifierClass(input)) {
let instance;
return async (request) => {
instance ??= new input();
return checkVerifiedTenant(await instance.verify(request));
};
}
if (hasVerify(input)) {
return async (request) => checkVerifiedTenant(await input.verify(request));
}
if (typeof input !== 'function') {
throw new TypeError('[@adonis-agora/media] `verifyTenant` must be a function, an object with verify() (a class instance), or a lazy import of one');
}
// A verifier function, or a lazy import factory: call it; a module that comes back names the
// verifier to use from then on.
const fn = input;
let lazy;
return async (request) => {
if (lazy)
return lazy(request);
const result = await fn(request);
const module = result && typeof result === 'object' ? result : undefined;
const named = module?.default ?? module?.tenantVerifier ?? module?.verify;
if (named !== undefined && !('partition' in module)) {
lazy = resolveTenantVerifier(named);
return lazy(request);
}
return checkVerifiedTenant(result);
};
}
/** Normalizes every accepted token source into {@link TenantToken}. */
export function resolveTenantToken(source) {
if (typeof source === 'string') {
if (source === '')
throw new Error('[@adonis-agora/media] tenant.token is empty');
return { get: async () => source };
}
if (typeof source === 'function') {
const reset = source.reset;
return {
get: () => source(),
...(typeof reset === 'function' ? { reset: () => reset.call(source) } : {}),
};
}
if (source && typeof source === 'object' && typeof source.get === 'function') {
const reset = source.reset ?? source.invalidate;
return {
get: () => source.get(),
...(typeof reset === 'function' ? { reset: () => reset.call(source) } : {}),
};
}
throw new Error('[@adonis-agora/media] tenant.token must be a string, a function returning a token, or an object with get()');
}
/** `Authorization: Bearer <token>`, or `undefined`. */
export function bearerOf(header) {
if (typeof header !== 'string')
return undefined;
return /^Bearer\s+(\S+)\s*$/i.exec(header)?.[1];
}
/** Constant-time comparison that does not leak where two secrets differ. */
function sameSecret(a, b) {
const left = Buffer.from(a);
const right = Buffer.from(b);
if (left.length !== right.length) {
timingSafeEqual(left, left);
return false;
}
return timingSafeEqual(left, right);
}
/**
* One shared secret per app, compared in constant time: the app names itself with `x-media-app`
* (the tenant client sends its `partition`), the secret proves it. For setups without authkit.
*
* ```ts
* verifyTenant: sharedSecretVerifier({ partitions: { 'entre-textos': env.get('MEDIA_ET_SECRET') } })
* ```
*/
export function sharedSecretVerifier(options) {
return (request) => {
const app = request.app ?? request.partition ?? request.tenant;
if (!request.token || !app || !Object.hasOwn(options.partitions, app))
return null;
const entry = options.partitions[app];
const config = typeof entry === 'string' ? { secret: entry } : entry;
if (!config.secret || !sameSecret(request.token, config.secret))
return null;
return {
partition: app,
capabilities: config.capabilities ?? ['media:read', 'media:write'],
};
};
}
//# sourceMappingURL=auth.js.map