UNPKG

@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

325 lines • 16.1 kB
import { adonisAuthIdentity, toAuthorizer, } from './access.js'; import { deliveryQueryString } from './delivery_signing.js'; import { ConversionArtifactMissingError, ConversionNotDefinedError, DeliverySignatureError, ImageSizeNotAllowedError, MediaAccessDeniedError, MediaNotFoundError, NotAnImageError, TransformNotReadyError, } from './errors.js'; import { deliverRecord, findUnscoped, imageOfRecord, streamOfRecord } from './internal_symbols.js'; import { isWebVtt, streamFormatOf } from './streaming.js'; /** * Authorization for media, wired to the app's identity (`access.identity` — authkit, AdonisJS * auth or your own) and the collections' `access` policies. `media.access` on the manager. * * The library still never decides authorization by itself: every rule comes from the app — * a collection's `access`, or an `authorize` passed in. This is the plumbing that applies them. */ export class MediaAccess { #library; #identity; constructor(options) { this.#library = options.library; this.#identity = options.identity ?? adonisAuthIdentity; } /** * The record a route serves. With tenancy on, a file of another tenant reads as missing, except * on a request whose delivery signature verifies for that id: the app signed it, so it is looked * up across tenants. An invalid or expired signature never widens the lookup (the file stays * "not found"). */ async #lookup(target, verified) { if (typeof target !== 'string') return target ?? null; const record = await this.#library.find(target); if (record) return record; let trusted = false; try { trusted = verified(target); } catch { trusted = false; } return trusted ? this.#library[findUnscoped](target) : null; } /** The current user per the configured identity resolver, or `null`. */ async subject(ctx) { return (await this.#identity(ctx)) ?? null; } /** * May the current user perform `action`? `target` is the record (read) or the collection a file * is going into (write). The rule is `authorize` when given, otherwise the collection's * `access[action]`; neither ⇒ `false`. */ async can(ctx, action, target, authorize) { return (await this.#decide(ctx, action, target, authorize)).allowed; } /** Resolve the subject ONCE and run the rule — so a denial's 401/403 matches what the rule saw. */ async #decide(ctx, action, target, authorize) { const collection = target.collection; const record = 'id' in target ? target : undefined; const rule = authorize ?? toAuthorizer(this.#library.collections.get(collection).access?.[action]); const subject = await this.subject(ctx); return { allowed: await rule({ ctx, action, collection, record, subject }), subject }; } /** * {@link can}, throwing {@link MediaAccessDeniedError} when refused — `401` for an anonymous * request, `403` otherwise. Use it in your own controllers and upload policies: * * ```ts * // DirectUploadPolicy.onInitiate * await media.access.authorize(ctx, 'write', { collection: 'avatar' }) * ``` */ async authorize(ctx, action, target, authorize) { const { allowed, subject } = await this.#decide(ctx, action, target, authorize); if (allowed) return; throw new MediaAccessDeniedError(action, target.collection, 'id' in target ? target.id : undefined, subject === null); } /** * `media.library.image(id)` for the current user: checks read access first (the collection's * `access.read`, or `authorize`), so the URLs it hands out — signed ones especially, which * carry their authorization — only ever reach someone allowed to see the file. */ async image(ctx, id, options = {}) { const { authorize, ...imageOptions } = options; const record = await this.#library.find(id); if (!record) throw new MediaNotFoundError(id); await this.authorize(ctx, 'read', record, authorize); // The record just authorized is the one rendered — no second lookup. return this.#library[imageOfRecord](record, imageOptions); } /** * `media.library.stream(id)` for the current user: checks read access first (the collection's * `access.read`, or `authorize`), then returns the HLS/DASH manifest URLs a player needs — for * `useMediaStream` from `@adonis-agora/media-react`. * * ```ts * return inertia.render('lessons/show', { video: await media.access.stream(ctx, lesson.videoMediaId) }) * ``` */ async stream(ctx, id, options = {}) { const { authorize, ...streamOptions } = options; const record = await this.#library.find(id); if (!record) throw new MediaNotFoundError(id); await this.authorize(ctx, 'read', record, authorize); return this.#library[streamOfRecord](record, streamOptions); } /** * Authorize and answer one request for a file of a streaming package (HLS or DASH) — the core * of {@link streamRoute}, for a controller that finds the record its own way. * * A request carrying a valid package signature (`?exp=&sig=`, from `media.library.stream()` * with `delivery.signing`) is served without asking the app again; anything else is authorized * like a read. A manifest is answered as text, with the signature carried onto its references * (a fresh one when the request was authorized by session), so the player's segment requests * stay authorized. Segments are redirected to storage or streamed, per `mode`. */ async serveStream(ctx, target, conversion, file, options = {}) { const { request, response } = ctx; const cacheControl = options.cacheControl ?? 'private, max-age=60'; try { const qs = request.qs(); const expires = stringParam(qs.exp); const signature = stringParam(qs.sig); const record = await this.#lookup(target, (mediaId) => this.#library.checkDeliverySignature({ mediaId, conversion, expires, signature }, { required: false })); if (!record) throw new MediaNotFoundError(typeof target === 'string' ? target : ''); const trusted = this.#library.checkDeliverySignature({ mediaId: record.id, conversion, expires, signature }, { required: false }); if (!trusted) await this.authorize(ctx, 'read', record, options.authorize); // Only a manifest (or a WebVTT pointing at package files) needs the signature its references // will carry. const query = !streamFormatOf(file) && !isWebVtt(file) ? '' : trusted ? deliveryQueryString({ expires: Number(expires), signature }).slice(1) : this.#library.streamQuery(record, conversion, options.expiresIn); const result = await this.#library.streamFile(record, conversion, file, { query, mode: options.mode, signedTtlSeconds: options.signedTtlSeconds, }); if (result.kind === 'manifest') { response.header('cache-control', cacheControl); response.header('content-type', result.contentType); return response.send(result.content); } if (result.kind === 'redirect') { response.header('cache-control', cacheControl); return response.redirect(result.url); } response.header('cache-control', options.segmentCacheControl ?? 'private, max-age=86400'); response.header('content-type', result.mimeType); if (result.size !== undefined) response.header('content-length', String(result.size)); return response.stream(result.stream); } catch (error) { return answerError(error, response); } } /** * A ready AdonisJS route handler for HLS/DASH packages — the read side of `transformers.video()`: * * ```ts * const serveStream = media.access.streamRoute() * router.get('/media/:id/stream/:conversion/*', serveStream) * ``` * * The URL mirrors the package: `/media/<id>/stream/<conversion>/<file>`, so the relative * references a manifest stores resolve back to this same route. See {@link serveStream}. */ streamRoute(options = {}) { return (ctx) => { const wildcard = ctx.params['*']; const file = Array.isArray(wildcard) ? wildcard.map(String).join('/') : String(ctx.params.file ?? wildcard ?? ''); return this.serveStream(ctx, String(ctx.params.id ?? ''), String(ctx.params.conversion ?? ''), file, options); }; } /** * Authorize and answer one media read — the core of {@link deliveryRoute}, for a controller that * finds the record its own way (a stable `/profiles/:id/photo` URL, a record looked up by its * owner): * * ```ts * async show(ctx) { * const [avatar] = await media.library.list('User', ctx.params.id, 'avatar') * return media.access.serve(ctx, avatar, { authorize: canSeeProfile }) * } * ``` * * `target` is the record, its id, or `null`/`undefined` (answered 404). Everything else is as in * {@link deliveryRoute}: the read is authorized unless the URL carries a valid signature, the query * (`?conversion`, `?w`, `?q`, `?exp`, `?sig`) and `Accept` are honoured, the file is redirected or * streamed with its headers, and the library's errors are answered as HTTP. */ async serve(ctx, target, options = {}) { const { request, response } = ctx; const cacheControl = options.cacheControl ?? 'private, max-age=60'; try { const qs = request.qs(); const signedFor = (mediaId) => ({ mediaId, conversion: stringParam(qs.conversion), width: stringParam(qs.w), quality: stringParam(qs.q), expires: stringParam(qs.exp), signature: stringParam(qs.sig), }); const record = await this.#lookup(target, (mediaId) => this.#library.checkDeliverySignature(signedFor(mediaId), { required: false })); if (!record) throw new MediaNotFoundError(typeof target === 'string' ? target : ''); const id = record.id; const signed = signedFor(id); // A valid signature is a prior authorization; an invalid or expired one is refused // (DeliverySignatureError). Unsigned requests are this caller's to authorize. const trusted = this.#library.checkDeliverySignature(signed, { required: false }); if (!trusted) await this.authorize(ctx, 'read', record, options.authorize); const deliverOptions = { ...(signed.conversion !== undefined ? { conversion: signed.conversion } : {}), ...(signed.width !== undefined && signed.width !== '' ? { width: signed.width, quality: signed.quality, accept: request.header('accept') ?? undefined, } : {}), ...(trusted ? { trusted: true } : {}), ...(options.mode !== undefined ? { mode: options.mode } : {}), ...(options.signedTtlSeconds !== undefined ? { signedTtlSeconds: options.signedTtlSeconds } : {}), }; // A record this call looked up itself is delivered as is; one the caller handed in is // re-read by id, as before (it may not be the stored one). const result = typeof target === 'string' ? await this.#library[deliverRecord](record, deliverOptions) : await this.#library.deliver(id, deliverOptions); response.header('cache-control', cacheControl); if (result.vary) response.header('vary', result.vary); if (result.kind === 'redirect') return response.redirect(result.url); response.header('content-type', result.mimeType); if (result.size !== undefined) response.header('content-length', String(result.size)); if (result.fileName) { response.header('content-disposition', inlineDisposition(result.fileName)); } return response.stream(result.stream); } catch (error) { return answerError(error, response); } } /** * A ready AdonisJS route handler that serves a media record — the delivery route every app was * hand-writing: * * ```ts * const serveMedia = media.access.deliveryRoute({ authorize: authorizers.owner() }) * router.get('/media/:id', serveMedia) * ``` * * - authorizes the read (`authorize`, or the collection's `access.read`; neither ⇒ refused), * unless the URL carries a valid `delivery.signing` signature — that signature IS the * authorization the app made when it issued the URL; * - passes `?conversion`, `?w`, `?q`, `Accept`, `?exp`, `?sig` through (on-demand resize, * format negotiation, signed URLs); * - redirects or streams per `delivery.mode`, with `Content-Type`, `Content-Length`, * `Content-Disposition: inline`, `Cache-Control` (private by default) and `Vary: Accept`; * - answers the library's errors as HTTP: 404 (unknown record or conversion), 400 (size not * allowed, not an image), 401/403 (not signed in / not allowed / bad signature). */ deliveryRoute(options = {}) { const param = options.param ?? 'id'; return (ctx) => this.serve(ctx, String(ctx.params[param] ?? ''), options); } } /** Answer a library error as `{ code, message }` with its HTTP status; rethrow anything else. */ function answerError(error, response) { const status = httpStatusOf(error); if (status === undefined) throw error; const { code, message } = error; const replied = response.status(status); return replied.json?.({ code, message }); } /** The HTTP status for an error the delivery route answers itself; `undefined` ⇒ rethrow. */ function httpStatusOf(error) { if (error instanceof MediaAccessDeniedError) return error.status; if (error instanceof DeliverySignatureError) return 403; if (error instanceof MediaNotFoundError) return 404; if (error instanceof ConversionNotDefinedError) return 404; if (error instanceof TransformNotReadyError) return 404; if (error instanceof ConversionArtifactMissingError) return 404; if (error instanceof ImageSizeNotAllowedError) return 400; if (error instanceof NotAnImageError) return 400; return undefined; } function stringParam(value) { const first = Array.isArray(value) ? value[0] : value; if (first === undefined || first === null) return undefined; return String(first); } /** `inline; filename="…"; filename*=UTF-8''…` — ASCII fallback plus the exact name (RFC 6266). */ function inlineDisposition(fileName) { const ascii = fileName.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_'); // RFC 5987 `attr-char` excludes ' ( ) * — which encodeURIComponent leaves alone; `'` would // even end the value early. const encoded = encodeURIComponent(fileName).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); return `inline; filename="${ascii}"; filename*=UTF-8''${encoded}`; } //# sourceMappingURL=media_access.js.map