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

307 lines • 15.3 kB
import { type KeyObject } from 'node:crypto'; import { type TenantTokenSource, type TenantVerifierInput, type VerifiedTenant } from '../topology/auth.js'; /** * The Redis channel the federated console talks to another app over: the console publishes a * command on `<prefix>-media-console`, every instance of the owning app hears it, the one that wins * `SET <prefix>-media-console-claim:<id> NX PX` runs it, and the answer comes back on * `<prefix>-media-console-reply`. Same design as `@adonis-agora/config`'s and * `@adonis-agora/durable`'s console commands, on channels of its own (`-media-`), so all of them * can share an app's prefix. * * Redis is not a trust boundary: every command (reads included: listing a disk and signing URLs * expose the app's storage) is authenticated, and so is every answer. See {@link RedisConsoleChannel}. */ /** This package's part of the channel names. */ export declare const CONSOLE_TOPIC = "media"; /** One command sent to the owning app. Arguments and answer are plain JSON. */ export interface MediaConsoleCommand { id: string; verb: string; args: unknown[]; /** Who acted in the console, for the owning app's log. Said by the console, not verified. */ actor?: string; /** * The capabilities the console's viewer holds, when the console says. They can only narrow what * the command may do (never widen what the console's token or the app's switches allow). */ capabilities?: string[]; /** When it was sent (ms since the epoch): a command older than a minute is refused. */ ts?: number; /** HMAC of every field above under the pair's shared secret (set by {@link RedisConsoleChannel}). */ mac?: string; /** * Token mode: who the owning app verified the console as (its token's partition and * capabilities). Set by the channel after verification, never taken from the wire. */ verified?: Pick<VerifiedTenant, 'partition' | 'capabilities' | 'clientId'> & { /** * An authkit app-call token (audience `urn:agora:app:<this app>`): `partition` is the CALLING * app (the console's), not this one, so the partition rule does not apply. */ appCall?: boolean; }; } /** * Verifies an authkit app-call token (audience `urn:agora:app:<this app>`): the calling app and * what it was granted here, or `null`. `@adonis-agora/authkit-client`'s * `appCallerVerifier().verifyToken` is one. */ export type AppCallVerifier = (token: string) => Promise<{ app: string; capabilities: string[]; clientId?: string; } | null>; /** The owning app's answer to a {@link MediaConsoleCommand}. */ export type MediaConsoleReply = ({ id: string; ok: true; data: unknown; } | { id: string; ok: false; error: { message: string; code?: string; status?: number; }; }) & { mac?: string; }; /** A shared secret: a string, or a Secret-like object (`env.get('X')` in AdonisJS). */ export type ChannelSecret = string | { release(): string; }; /** The owning app refused the console's token (the console drops its cached token). */ export declare const UNAUTHORIZED_CONSOLE = "federated-console-unauthorized"; /** How long a failed app-call token, or an automatic per-app choice, is kept before trying again. */ export declare const CONSOLE_RETRY_MS: number; /** Console side, automatic: which way to reach one app (§13a), decided lazily and cached. */ export interface ConsoleModeChooser { choose(): Promise<'token' | 'crypto'>; /** Forget the decision: the next command decides again. */ reset(): void; /** * Keep `way` as the decision for the next 5 minutes (the token way could not mint its token: * crypto, without a failing mint per command, §13a/§13b). */ settle(way: 'token' | 'crypto'): void; } /** An app's console-command key pair. The public half is what the console seals commands to. */ export interface ConsoleCommandKeys { /** The public key (base64url, 32 bytes): `controlPlane.publicKey` on the console. */ publicKey: string; /** A short id of the public key, carried in each sealed command. */ kid: string; /** @internal The private half. Never leaves this app. */ privateKey: KeyObject; } /** The 8-character id every Agora lib's boot log shows for a command key (never the key). */ export declare function shortKeyId(publicKey: string): string; /** Whether `value` reads as an X25519 public key (base64url of 32 bytes). */ export declare function isConsolePublicKey(value: unknown): value is string; /** * This app's console-command key pair, derived from its `APP_KEY` and the channel's `prefix`: the * same `APP_KEY` always gives the same key, so every instance opens what the console sealed. Print * the public half with `node ace media:console-key`. */ export declare function consoleCommandKeys(appKey: ChannelSecret, prefix: string): ConsoleCommandKeys; /** * The app's `APP_KEY`, the same way in every Agora lib (§13c): `config/app.ts`'s `appKey`, else the * default entry of `config/encryption.ts` (AdonisJS 7, lazy providers resolved), else the * `APP_KEY` environment variable. A `Secret` (`.release()`) or a string; a source that throws counts * as "no key here"; never logged. */ export declare function appKeyOf(app: unknown): Promise<string | undefined>; /** * How a sealed command is encrypted: to the app's command key derived from its `APP_KEY`, or with a * key of `@adonis-agora/crypto` (the Hub's, or the app's own). Either way only the owning app * opens it, and the AAD binds it to this channel and this command id. */ export interface ConsoleSealer { /** Whether `sealed` is this sealer's ciphertext (so the app knows which one opens it). */ owns(sealed: string): boolean; seal(plaintext: string, aad: string): Promise<string>; open(sealed: string, aad: string): Promise<string>; } /** The `encrypt`/`decrypt` pair `@adonis-agora/crypto` exposes (`crypto.client`, `serviceCipher`). */ export interface ConsoleCipher { encrypt(input: { key: string; plaintext: string; aad?: string; context?: string; }): Promise<{ ciphertext: string; }>; decrypt(input: { key: string; ciphertext: string; aad?: string; context?: string; }): Promise<{ plaintext: string; }>; } /** * A cipher, or a function returning one: `config/media.ts` is read before `@adonis-agora/crypto` * is ready, so `() => crypto.client!` (or `() => serviceCipher(crypto.service, 'app')`) defers it * to the first command. */ export type ConsoleCipherSource = ConsoleCipher | (() => ConsoleCipher | Promise<ConsoleCipher>); /** The `@adonis-agora/crypto` key console commands are sealed with, unless another is named. */ export declare const CONSOLE_CRYPTO_KEY = "console-media"; /** Seals with an `@adonis-agora/crypto` key: whoever may `encrypt` with it sends, the app opens. */ export declare function cryptoConsoleSealer(options: { cipher: ConsoleCipherSource; key?: string | undefined; owns?: ((ciphertext: string) => boolean) | undefined; }): ConsoleSealer; /** The app's command public key: the string itself, or a function returning it. */ export type ConsolePublicKeySource = string | (() => string | Promise<string>); /** Seals to the app's X25519 command key: the console side (the key from the console's config). */ export declare function appKeySealerTo(recipient: ConsolePublicKeySource): ConsoleSealer; /** Opens with the app's X25519 command key pair (derived from its `APP_KEY`): the app side. */ export declare function appKeySealer(keys: ConsoleCommandKeys): ConsoleSealer; /** How one channel authenticates: what it sends with, and every way it accepts commands. */ export interface ConsoleChannelAuthOptions { /** Shared-secret mode: the same value on the console and on the app (16+ characters). */ secret?: ChannelSecret | undefined; /** * Sealed mode with `@adonis-agora/crypto`, both sides: the cipher (`crypto.client`, or * `serviceCipher(crypto.service, partition)` where crypto is embedded) and the key * (`console-media` by default). The console needs `encrypt` on it, the app `decrypt`. */ crypto?: { cipher: ConsoleCipherSource; key?: string | undefined; /** Whether a ciphertext is this cipher's (default: `agora:ct1:<key>:`), for a KMS of your own. */ owns?: ((ciphertext: string) => boolean) | undefined; } | undefined; /** App side: verifies authkit app-call tokens (`appCallerVerifier().verifyToken`). */ verifyAppCall?: AppCallVerifier | undefined; /** * App side, with `crypto` and `verifyTenant` both set: whether a crypto-sealed command must also * carry a token `verifyTenant` accepts. Default `true`. `false` when `verifyTenant` is only there * for the token mode (a control plane's own verifier, automatic crypto): whoever may encrypt with * the key is the console, as with crypto alone. */ cryptoRequiresToken?: boolean | undefined; /** Console side: the token each command carries (`authkitTenantToken(...)`). */ token?: TenantTokenSource | undefined; /** * Console side, crypto mode with an automatic token (§13b): called (once until it works again) * when the token cannot be minted; the command goes crypto-only, minting is retried in 5 min. */ tokenOptional?: ((reason: string, code?: string) => void) | undefined; /** Console side: what to add when a required token cannot be minted (the authkit grant). */ tokenHint?: string | undefined; /** * Console side, automatic with both ways possible (§13a): picks token (sealed to `recipient`) * or crypto per command, cached by the chooser. */ chooser?: ConsoleModeChooser | undefined; /** * Console side, token mode without `crypto`: the app's command public key (`node ace * media:console-key` on the app prints it). Taken from the console's own config, never from Redis. */ recipient?: ConsolePublicKeySource | undefined; /** App side, token mode without `crypto`: this app's command key pair (from its `APP_KEY`). */ keys?: ConsoleCommandKeys | undefined; /** App side: verifies the console's token (`authkitTenantVerifier(...)`). */ verifyTenant?: TenantVerifierInput | undefined; /** * App side, token mode: this app's name as the console's token names it (its `partition`), * handed to `verifyTenant` as the app the command is for. The command handler checks it. */ partition?: string | undefined; } /** An `ioredis` client: pub/sub needs a dedicated connection, made with `duplicate()`. */ export interface IoredisLike { publish(channel: string, message: string): Promise<unknown>; set?(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<unknown>; duplicate(): IoredisSubscriberLike; } export interface IoredisSubscriberLike { subscribe(...channels: string[]): unknown; on(event: 'message', listener: (channel: string, message: string) => void): unknown; disconnect?(): void; } /** An `@adonisjs/redis` connection: it keeps its own subscriber and hands each payload over. */ export interface AdonisRedisLike { publish(channel: string, message: string): Promise<unknown>; set?(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<unknown>; subscribe(channel: string, handler: (message: string) => void): unknown; unsubscribe?(channel: string): unknown; } export type RedisLike = IoredisLike | AdonisRedisLike; /** How long a command waits for its answer by default. */ export declare const MEDIA_CONSOLE_TIMEOUT_MS = 15000; /** A command the owning app refused or failed, or that nobody answered. */ export declare class MediaConsoleChannelError extends Error { readonly code: string; constructor(message: string, code: string); } /** * A command this app refused before running it, with the reason every Agora lib logs (§11b): * `not JSON`, `no command id`, `did not open with this app's key`, `bad signature`, `stale`, * `replayed`, `token refused`, `capabilities-required`, or `mode not accepted here (…)`. */ export declare class ConsoleCommandRefused extends MediaConsoleChannelError { readonly reason: string; constructor(reason: string); } /** Nobody listens on the app's channel, or nobody answered in time. */ export declare const APP_UNREACHABLE = "federated-app-unreachable"; /** The channel has no authentication, so it neither sends nor answers commands. */ export declare const UNSIGNED_CHANNEL = "federated-channel-unsigned"; export declare class RedisConsoleChannel { #private; readonly prefix: string; /** * Redis is not a trust boundary, so a channel neither sends nor answers commands without one of: * * - `crypto` — commands sealed with an `@adonis-agora/crypto` key (the console may encrypt with it, * the app decrypt), optionally with a `token` the app checks with `verifyTenant`; * - a `token` sealed to the app's command key (`recipient` on the console, `keys` on the app, * from its `APP_KEY`), checked with `verifyTenant` (authkit, typically); * - `secret` — shared by the console and the app (the same value on both sides). */ constructor(options: { client: RedisLike; prefix: string; } & ConsoleChannelAuthOptions); /** Whether this channel can send commands (crypto, a token and the app's key, or a secret). */ get signed(): boolean; /** Whether this channel answers commands in at least one authenticated way. */ get answers(): boolean; get commandChannel(): string; get replyChannel(): string; /** * Send `command` to the owning app and wait for its answer. Rejects at once when no instance * listens (`PUBLISH` reached nobody) and after `timeoutMs` when nobody answers. An answer that * does not carry this command's MAC (a forged one) is ignored. */ send(command: MediaConsoleCommand, options?: { timeoutMs?: number | undefined; }): Promise<MediaConsoleReply>; /** * Answer the commands other apps' consoles send this app. Every instance subscribes; the one that * wins `SET <prefix>-media-console-claim:<id> NX` runs the command and publishes the answer, so a * command runs once however many processes the app has. Throws when the channel has no * authentication, or when the client cannot run that `SET`: a command never runs without the * claim. */ answer(handler: (command: MediaConsoleCommand) => Promise<unknown>, options?: { onError?: (error: unknown) => void; }): Promise<void>; /** Stop listening and fail the commands still waiting for an answer. */ close(): Promise<void>; } /** * The Redis client for `connection` (an `@adonisjs/redis` connection name; omit for its default), * resolved through the container's `redis` binding. */ export declare function resolveRedisConnection(container: { make(binding: string): Promise<unknown>; }, connection: string | undefined): Promise<RedisLike>; //# sourceMappingURL=redis_channel.d.ts.map