@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
398 lines • 21.1 kB
TypeScript
import { Readable } from 'node:stream';
import { DashboardError, DashboardService } from '../dashboard/service.js';
import type { CollectionFilter, CollectionListResponse, CollectionsSummaryResponse, CursorParams, DiskListResponse, MediaDetailResponse, MediaEntry, ObjectDetailResponse, ObjectInsightsResponse, ObjectListResponse, Topology, UploadDetailResponse, UploadFilter, UploadListResponse } from '../dashboard/types.js';
import type { MediaStore } from '../media_store.js';
import type { UploadSessionStore } from '../resumable_upload.js';
import type { StoreFactory } from '../stores/factory.js';
import type { TenantTokenSource } from '../topology/auth.js';
import type { UploadSessionStoreFactory } from '../upload_sessions/factory.js';
import { type ExplicitConsoleCrypto } from './console_auth.js';
import { type ChannelSecret, type MediaConsoleCommand, RedisConsoleChannel } from './redis_channel.js';
/**
* The federated media console: one app's media console also shows the media of other apps, each of
* which keeps its own database tables, its own disks and its own credentials. The console reads an
* app's records and upload sessions straight from that app's tables, and asks the app itself (over
* Redis) for what needs its disks: listing them, signing URLs, and the actions.
*/
/** One other app shown in this console (`config/media_dashboard.ts` → `apps`). */
export interface FederatedConsoleApp {
/** The name shown in the app selector. Defaults to the key. */
label?: string | undefined;
/**
* That app's media store: `stores.lucid({ connection, schema })` naming where ITS `media` table
* is. Only read (never created or altered): give the connection's role `SELECT` on it.
*/
store: StoreFactory | MediaStore;
/**
* That app's resumable upload sessions: `uploadSessions.lucid({ connection, schema })`. Omit and
* the Uploads page shows nothing for that app. Only read.
*/
uploadSessions?: UploadSessionStoreFactory | UploadSessionStore | undefined;
/**
* Where that app answers (its `consoleCommands` in `config/media.ts`): the `@adonisjs/redis`
* connection to publish on, the app's `prefix`, and how this console proves itself to the app
* (one of `crypto`, `token` + `publicKey`, or `secret`; the app answers nothing otherwise).
*/
controlPlane: FederatedControlPlane | RedisConsoleChannel;
/**
* That app's public origin (`https://app.example.com`). An app whose console serves its objects
* through itself (`objectUrls: 'proxy'`) hands back paths, and they are opened on this origin
* (where the viewer must be signed in to that app). Not needed when the app signs URLs straight
* to its storage.
*/
origin?: string | undefined;
/**
* Serve that app's object bytes from THIS console (same origin) instead of sending the browser
* to the app. The console asks the app for the object's URL as usual, then fetches it itself: a
* path on {@link origin} (an app with `objectUrls: 'proxy'`) with `headers`, a signed URL as is.
* Previews, thumbnails and "Open" then work for a viewer with no session in that app, and under a
* CSP that only allows this origin's images.
*
* `headers` is what that app needs to accept the request, e.g. a service token its console's
* `authorize` takes (`authorizeAgoraCaller` in `@adonis-agora/media/dashboard`). They are sent only to `origin`.
*
* ```ts
* proxyObjects: { headers: async () => ({ authorization: `Bearer ${await token()}` }) },
* ```
*
* `true` fetches with no extra headers (an outbound interceptor may add them). Default: off, the
* browser is sent to the app's URL.
*/
proxyObjects?: boolean | FederatedObjectProxy | undefined;
/**
* Send this console's actions on that app's media (delete, copy, move, folders, delete record,
* cancel upload) to the app's own console API over HTTP, at {@link origin}. The app runs each one
* with its own store and disks, as if from its own console. Needs `origin`.
*
* The app's console must let this console in for those routes: `authorizeAgoraCaller({ actions:
* true })` there, the `media:objects:write` capability for this console's service token, and
* `actions: true` in its config/media_dashboard.ts.
*
* ```ts
* proxyActions: { apiPath: '/media/api' },
* ```
*
* `true` uses the defaults. `headers` defaults to `proxyObjects.headers`. Turns actions on for
* this app whatever this console's own `actions` says; `actions: false` on the entry turns them
* off again. Without it, actions go over {@link controlPlane} (when this console has `actions` on
* and the app answers them, `consoleCommands.actions`).
*/
proxyActions?: boolean | FederatedActionProxy | undefined;
/**
* Whether this console runs actions on that app's media. Default `true`, like every Agora
* console's entries: the app still decides (`consoleCommands.actions`, off by default), and an
* entry this console cannot authenticate to fails the boot. `false`: browse only.
*/
actions?: boolean | undefined;
/** How long a command waits for the app to answer, in ms. Default 15 000. */
timeoutMs?: number | undefined;
/**
* That app's name in `@adonis-agora/crypto` (its crypto partition): where automatic crypto mode
* keeps the `console-media` key. Default: the entry's key in `apps`. It must equal the app's crypto
* partition (its `config/crypto.ts` name, or its tenant partition on the Hub).
*/
partition?: string | undefined;
}
/** {@link FederatedConsoleApp.controlPlane}: where the app answers, and how this console signs. */
export interface FederatedControlPlane {
/** The `@adonisjs/redis` connection. Defaults to its default connection. */
connection?: string | undefined;
/** The app's `consoleCommands.prefix`. */
prefix: string;
/**
* Shared-secret mode: the secret shared with that app (its `consoleCommands.secret`), 16+
* characters. Use it when there is neither authkit nor `@adonis-agora/crypto`.
*/
secret?: ChannelSecret | undefined;
/**
* Token mode: this console's token for that app, e.g. `authkitTenantToken({ issuer, clientId,
* clientSecret, resource: 'urn:agora:media' })` of a service-tenant client whose `partition` is
* that app and whose capabilities say what this console may do there (`media:objects:read` to
* browse, `media:objects:write` for actions). The app checks it with its
* `consoleCommands.verifyTenant`. Without `crypto`, set {@link publicKey} too. Or a function of
* your own (`() => Promise<string>`, any IdP). Nothing to set with authkit's calls between apps
* (`service` in config/authkit_client.ts): this console's app-call token for that app is sent
* automatically. `false` turns that off.
*/
token?: TenantTokenSource | false | undefined;
/**
* Token mode without `crypto`: the app's console-command public key, which `node ace
* media:console-key` prints on that app (it also logs it at boot). Commands and the token are
* sealed to it. It is not secret, but take it from your own config: never from Redis.
*/
publicKey?: string | (() => string | Promise<string>) | undefined;
/**
* Sealed with `@adonis-agora/crypto`. Nothing to set where crypto is embedded in this app (the
* Hub): commands are then encrypted with the key `console-media` in the app's
* {@link FederatedConsoleApp.partition} automatically. Set it explicitly on a console whose crypto
* is a tenant: a cipher for a key of that app (`console-media` by default) it may `encrypt` with
* and the app may `decrypt`. Combine with `token` when the app also checks one
* (`consoleCommands.verifyTenant`). `false` turns automatic mode off.
*/
crypto?: ExplicitConsoleCrypto | false | undefined;
}
/** {@link FederatedConsoleApp.proxyActions} as an object. */
export interface FederatedActionProxy {
/**
* Request headers for the app's own origin (a service token). Asked on every action. Default:
* `proxyObjects.headers`.
*/
headers?: (() => Record<string, string> | Promise<Record<string, string>>) | undefined;
/** Where the app's console API is mounted on its origin. Default `/media/dashboard/api`. */
apiPath?: string | undefined;
/** How long to wait for the app to answer an action, in ms. Default 30 000. */
timeoutMs?: number | undefined;
}
/**
* Whether a console runs actions on the app `entry`: its `actions`, default `true` (the app's own
* `consoleCommands.actions` still gates them). `_consoleActions` (the console's own switch, for its
* own app) no longer applies to entries.
*/
export declare function federatedAppActions(entry: FederatedConsoleApp, _consoleActions?: boolean): boolean;
/** {@link FederatedConsoleApp.proxyObjects} as an object. */
export interface FederatedObjectProxy {
/** Extra request headers for the app's own origin (a service token). Asked on every fetch. */
headers?: (() => Record<string, string> | Promise<Record<string, string>>) | undefined;
/** How long to wait for the app to start answering, in ms. Default 30 000. */
timeoutMs?: number | undefined;
}
/** What a federated app's key may look like (it travels in the URL as `?app=`). */
export declare const FEDERATED_APP_KEY: RegExp;
/**
* Checks one `apps` entry at boot, so a misconfigured app fails the boot instead of the first
* request that picks it. `redisConnections` are the names in `config/redis.ts` (`undefined`: no
* Redis config to check against).
*/
export declare function validateFederatedConsoleApp(key: string, entry: FederatedConsoleApp, redisConnections: {
names: string[];
default: string | undefined;
} | undefined,
/** Whether authkit's key directory can hand this console the app's command key. */
options?: {
keyDirectory?: boolean;
}): void;
/** The commands that only read. */
export declare const READ_VERBS: readonly ['topology', 'disks', 'objects', 'object', 'objectInsights', 'objectUrls'];
/** The commands that change something: run only when the owning app sets `actions: true`. */
export declare const ACTION_VERBS: readonly ['deleteMediaRecord', 'abortUpload', 'remove', 'copy', 'move', 'createFolder', 'deleteFolder', 'copyFolder', 'moveFolder'];
export type MediaConsoleVerb = (typeof READ_VERBS)[number] | (typeof ACTION_VERBS)[number];
/** The action verbs, as the app's console API takes them (`proxyActions`): `POST <apiPath><path>`. */
type ActionVerb = (typeof ACTION_VERBS)[number];
/** Each action as a request on the app's console API: the path and the JSON body. */
export declare function federatedActionRequest(verb: ActionVerb, args: unknown[]): {
path: string;
body: Record<string, unknown>;
};
/** The header a forwarded action names who asked for it in (the app logs it). */
export declare const ACTOR_HEADER = "x-agora-actor";
/**
* A viewer name fit for a header and a log line: control characters (CR/LF…) become spaces,
* anything outside printable ASCII is percent-encoded, at most 200 characters.
*/
export declare function sanitizeActor(actor: unknown): string | undefined;
/**
* The statuses of the app's own answer to an action that reach the viewer as they are, with the
* app's message: what the viewer can act on. Any other refusal is a `502`.
*/
export declare const RELAYED_ACTION_STATUSES: ReadonlySet<number>;
/** `<apiPath><route>` with exactly one `/` between them (`/`, `/media/api/`, `/media//api`). */
export declare function joinApiPath(apiPath: string, route: string): string;
/** A command this app does not answer (unknown verb). Answered `501` by the console. */
export declare const UNSUPPORTED = "unsupported-request";
/**
* What a console's token must hold, in token mode, to read this app's storage (list disks and
* objects, sign URLs) over the console channel. The same capability `authorizeAgoraCaller` asks for
* object bytes.
*/
export declare const CONSOLE_READ_CAPABILITY = "media:objects:read";
/** What a console's token must hold, in token mode, to run actions (with `actions: true` here). */
export declare const CONSOLE_WRITE_CAPABILITY = "media:objects:write";
/**
* Every console capability: what the console sends for a viewer when its `authorize` does not say
* (`capabilities` in its answer narrows it). `media:console:read`/`write`, `media:console:*`,
* `media:*` and `*` grant the same.
*/
export declare const CONSOLE_CAPABILITIES: readonly string[];
/** A command that came without the viewer's capabilities (an older or a forged console). */
export declare const MISSING_CAPABILITIES = "capabilities-required";
/**
* Run the commands another app's federated console sends this app, against this app's own console
* service (`service()` builds it with every tenant in view). Mutating verbs run only with
* `actions`; mutating commands are logged with who sent them.
*
* Every command carries the viewer's capabilities (the console always sends them); one without is
* refused (`403`), never taken as "everything". Reads need `media:objects:read`, actions
* `media:objects:write` (and `actions` here). In token mode (the channel verified the console's
* token and set `verified`) the token is the ceiling: its `partition` must be `partition` (this
* app), and what it grants is intersected with the viewer's capabilities.
*/
export declare function mediaConsoleCommandHandler(options: {
service: () => Promise<DashboardService>;
actions: boolean;
/** This app's name as a console's token must name it (token mode). Required for token mode. */
partition?: string | undefined;
log?: ((line: string) => void) | undefined;
}): (command: MediaConsoleCommand) => Promise<unknown>;
/** Another app as the console sees it: its stores and its command channel. Built once per app. */
export declare class FederatedApp {
#private;
readonly id: string;
readonly label: string;
readonly store: MediaStore;
readonly sessions: UploadSessionStore | undefined;
readonly channel: RedisConsoleChannel;
readonly origin: string | undefined;
readonly timeoutMs: number | undefined;
/** Set when this console serves the app's object bytes itself (`proxyObjects`). */
readonly proxy: FederatedObjectProxy | undefined;
/** Set when this console sends its actions to the app's console API (`proxyActions`). */
readonly actionProxy: (Omit<FederatedActionProxy, 'apiPath' | 'timeoutMs'> & {
apiPath: string;
timeoutMs: number;
}) | undefined;
constructor(options: {
id: string;
label?: string | undefined;
store: MediaStore;
sessions?: UploadSessionStore | undefined;
channel: RedisConsoleChannel;
origin?: string | undefined;
timeoutMs?: number | undefined;
proxyObjects?: boolean | FederatedObjectProxy | undefined;
proxyActions?: boolean | FederatedActionProxy | undefined;
/** For tests. Default: the global `fetch`. */
fetch?: typeof fetch | undefined;
});
/** Send `verb` to the app and return its answer; errors become the console's HTTP answers. */
send(verb: MediaConsoleVerb, args: unknown[], actor?: string, capabilities?: readonly string[]): Promise<unknown>;
/** `url` as the browser can open it: absolute as is, a path on the app's {@link origin}. */
absolute(url: unknown): string | null;
/**
* Fetch the bytes at `url` (what the app answered for an object) for this console to serve. A
* path goes to the app's {@link origin} with the `proxyObjects` headers; a signed URL is fetched
* as is, with none. The app's `404` stays a `404`; any other refusal is a `502` (cause logged).
*/
fetchBytes(url: string): Promise<{
stream: Readable;
contentType: string;
size: number;
}>;
/**
* Run an action in the app through its console API (`proxyActions`): `POST` on its {@link origin}
* with the headers, `redirect: 'manual'`. The app's `404` and its answers to a bad request stand;
* a refusal (`401`/`403`), a redirect or a failure is a `502` (cause logged); no answer is a `503`.
*/
forwardAction(verb: ActionVerb, args: unknown[], actor?: string): Promise<void>;
close(): Promise<void>;
}
/** An error the owning app could not be asked about (`503`), refused (`501`) or failed (`502`). */
export declare class FederatedAppError extends DashboardError {
/** The owning app's own message, for this app's log (a `502` does not show it to the browser). */
readonly detail: string | undefined;
constructor(message: string, status: 501 | 502 | 503, detail?: string);
}
/**
* Build one configured app: its stores (read-only) and its command channel. The channel signs the
* way the entry says, or, with nothing said and `@adonis-agora/crypto` embedded in this app, with
* the key `console-media` in the app's partition (automatic crypto mode).
*/
export declare function buildFederatedMediaApp(id: string, config: FederatedConsoleApp, app: {
container: {
make(binding: string): Promise<unknown>;
hasBinding?(b: string): boolean;
};
}): Promise<FederatedApp>;
/**
* The console's service over another app: the same surface as {@link DashboardService}. Records,
* collections and upload sessions come from that app's tables; disks, object URLs and every action
* go to that app (over Redis, or its console API with `proxyActions`). `actions` is THIS console's
* switch for that app: an action this console has off never leaves.
*/
export declare class FederatedConsoleService {
#private;
constructor(app: FederatedApp, options: {
actions: boolean;
actor?: string | undefined;
/**
* What the viewer may do on that app (its `authorize`'s `capabilities`), sent with every
* command. Default: every console capability ({@link CONSOLE_CAPABILITIES}).
*/
capabilities?: readonly string[] | undefined;
/**
* This console's own byte route for the app's object (`<apiBase>/object/raw?app=…`). With it
* and the app's `proxyObjects`, the URLs handed to the browser point here.
*/
rawUrl?: ((disk: string, key: string) => string) | undefined;
});
/** The app's disks count (`0` while it does not answer), uploads and this console's actions. */
topology(): Promise<Topology>;
disks(): Promise<DiskListResponse>;
objects(disk: string, params?: CursorParams & {
prefix?: string;
}): Promise<ObjectListResponse>;
/** `true` when this console serves the app's bytes itself ({@link objectStream}). */
get servesBytes(): boolean;
object(disk: string, key: string): Promise<ObjectDetailResponse>;
/** Where the browser opens the object's bytes: the app's URL for it (absolute), or a `501`. */
objectRedirect(disk: string, key: string): Promise<string>;
/** The object's bytes, fetched from the app (`proxyObjects`); a `501` without it. */
objectStream(disk: string, key: string): Promise<{
stream: Readable;
contentType: string;
size: number;
}>;
objectInsights(disk: string, key: string): Promise<ObjectInsightsResponse>;
putObject(): Promise<void>;
uploads(filter?: UploadFilter & {
order?: 'asc' | 'desc';
}): Promise<UploadListResponse>;
uploadDetail(id: string): Promise<UploadDetailResponse>;
abortUpload(id: string): Promise<void>;
collections(params?: CollectionFilter & CursorParams): Promise<CollectionListResponse>;
collectionsSummary(): Promise<CollectionsSummaryResponse>;
mediaEntry(id: string): Promise<MediaEntry>;
/**
* One record from the app's table, with a URL per conversion asked of the app. While the app does
* not answer, the record still shows, without them.
*/
mediaRecord(id: string): Promise<MediaDetailResponse>;
deleteMediaRecord(id: string): Promise<void>;
copy(body: {
disk: string;
from: string;
to: string;
toDisk?: string;
}): Promise<void>;
move(body: {
disk: string;
from: string;
to: string;
toDisk?: string;
}): Promise<void>;
remove(body: {
disk: string;
keys: string[];
}): Promise<void>;
createFolder(body: {
disk: string;
prefix: string;
}): Promise<void>;
deleteFolder(body: {
disk: string;
prefix: string;
}): Promise<void>;
copyFolder(body: {
disk: string;
from: string;
to: string;
toDisk?: string;
}): Promise<void>;
moveFolder(body: {
disk: string;
from: string;
to: string;
toDisk?: string;
}): Promise<void>;
}
export {};
//# sourceMappingURL=console.d.ts.map