diff --git a/README.md b/README.md index 97e7527..67b5f9f 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,11 @@ gets promoted into the platform, with its domain moving into a runtime context a a list (and a canvas board in TypeScript), an `add_item` agent tool and a `session.placed` subscription. - `templates/javascript`: the same checklist with its canvas board, in JavaScript that Node runs as it is, and a `GUIDE.md` for an agent building from it. It is the template rh's plug-in creator scaffolds from. +- `plugins/voice`: speech to text and text to speech for the composer, on `http/transcribe` and `http/speak`, through + the STT and TTS servers named in its settings. It replaces rh's `/api/voice` routes. +- `plugins/files`: the Files page's and the workflow editor's file calls on `http/list`, `http/download`, `http/upload`, + `http/mkdir`, `http/rename` and `http/delete`, with the queries, bodies and errors of rh's `/api/files` routes, which it + replaces. Every path stays inside the folder its `root` setting names, links included. ## The contract @@ -56,6 +61,9 @@ Plugin::new(state) .await ``` +The TypeScript SDK also serves the `http/` routes: `http: { speak: (request) => response }` gets each +`/http/speak/…` call as a web `Request`, body unread, and streams the `Response` it returns back through rh. + On Linux rh confines a plug-in with Landlock to its own directory, its data and run folders and the program it runs, so a TypeScript plug-in runs a bundle (`npm run build` writes `dist/plugin.js` with esbuild) rather than sources that import from outside its directory, and a Rust plug-in runs its release binary. diff --git a/package-lock.json b/package-lock.json index adedb40..a00b250 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,8 @@ "name": "rivethub-plugins", "workspaces": [ "packages/*", - "templates/typescript" + "templates/typescript", + "plugins/*" ], "devDependencies": { "@biomejs/biome": "2.5.15", @@ -1132,6 +1133,10 @@ } } }, + "node_modules/files": { + "resolved": "plugins/files", + "link": true + }, "node_modules/js-yaml": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", @@ -1283,6 +1288,10 @@ "dev": true, "license": "MIT" }, + "node_modules/voice": { + "resolved": "plugins/voice", + "link": true + }, "packages/contract": { "name": "@rivethub/contract", "version": "0.7.0" @@ -1297,6 +1306,24 @@ "rivethub-plugin-dev": "src/dev.ts" } }, + "plugins/files": { + "version": "0.1.0", + "dependencies": { + "@rivethub/plugin-sdk": "0.7.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } + }, + "plugins/voice": { + "version": "0.1.0", + "dependencies": { + "@rivethub/plugin-sdk": "0.7.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } + }, "templates/typescript": { "name": "checklist-ts", "version": "0.1.0", diff --git a/package.json b/package.json index 3811e67..2de4e6b 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ }, "workspaces": [ "packages/*", - "templates/typescript" + "templates/typescript", + "plugins/*" ], "scripts": { "check": "npm run lint && npm run typecheck && npm test && npm run contract:check && npm run privacy && npm run rust", diff --git a/packages/plugin-sdk/src/plugin.ts b/packages/plugin-sdk/src/plugin.ts index 0f41c56..37b7f73 100644 --- a/packages/plugin-sdk/src/plugin.ts +++ b/packages/plugin-sdk/src/plugin.ts @@ -32,6 +32,7 @@ export interface Plugin { > events?: EventHandlers jobs?: Record Awaitable> + http?: Record Awaitable> settings?: (values: Settings) => Awaitable } diff --git a/packages/plugin-sdk/src/serve.ts b/packages/plugin-sdk/src/serve.ts index 4993208..91a3a7d 100644 --- a/packages/plugin-sdk/src/serve.ts +++ b/packages/plugin-sdk/src/serve.ts @@ -1,7 +1,12 @@ -import { createServer, type Server, type ServerResponse } from 'node:http' +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import { Readable } from 'node:stream' +import { pipeline } from 'node:stream/promises' +import type { ReadableStream as NodeReadableStream } from 'node:stream/web' import { type Plugin, type Reply, router } from './plugin.ts' import { connect, pluginEnv } from './rivethub.ts' +type HttpHandler = NonNullable[string] + function write(response: ServerResponse, reply: Reply): void { if (reply.body === undefined) { response.writeHead(reply.status).end() @@ -12,11 +17,50 @@ function write(response: ServerResponse, reply: Reply): void { } } +function httpHandler(plugin: Plugin, url: string): HttpHandler | undefined { + const [kind, name] = new URL(url, 'http://plugin').pathname.split('/').filter(Boolean) + if (kind !== 'http' || name === undefined || plugin.http === undefined) return undefined + return Object.hasOwn(plugin.http, name) ? plugin.http[name] : undefined +} + +function webRequest(incoming: IncomingMessage): Request { + const headers = new Headers() + const raw = incoming.rawHeaders + for (let index = 0; index + 1 < raw.length; index += 2) headers.append(raw[index] ?? '', raw[index + 1] ?? '') + const method = incoming.method ?? 'GET' + const body = method === 'GET' || method === 'HEAD' ? null : (Readable.toWeb(incoming) as ReadableStream) + return new Request(new URL(incoming.url ?? '/', 'http://plugin'), { method, headers, body, duplex: 'half' }) +} + +async function relay(handler: HttpHandler, incoming: IncomingMessage, response: ServerResponse): Promise { + let answer: Response + try { + answer = await handler(webRequest(incoming)) + } catch (error) { + answer = new Response(error instanceof Error ? error.message : String(error), { + status: 500, + headers: { 'content-type': 'text/plain; charset=utf-8' }, + }) + } + const headers = Object.fromEntries(answer.headers) + if (!incoming.complete) headers.connection = 'close' + response.writeHead(answer.status, headers) + if (answer.body === null) { + response.end() + return + } + await pipeline(Readable.fromWeb(answer.body as NodeReadableStream), response).catch((error: unknown) => + response.destroy(error instanceof Error ? error : undefined), + ) +} + export async function serve(plugin: Plugin, env: NodeJS.ProcessEnv = process.env): Promise { const { socket } = pluginEnv(env) if (plugin.settings !== undefined) await plugin.settings((await connect(env).self()).settings) const route = router(plugin) const server = createServer(async (request, response) => { + const handler = httpHandler(plugin, request.url ?? '/') + if (handler !== undefined) return relay(handler, request, response) const chunks: Buffer[] = [] for await (const chunk of request) chunks.push(chunk as Buffer) write(response, await route(request.method ?? 'GET', request.url ?? '/', Buffer.concat(chunks).toString('utf8'))) diff --git a/plugins/files/package.json b/plugins/files/package.json new file mode 100644 index 0000000..fb93f81 --- /dev/null +++ b/plugins/files/package.json @@ -0,0 +1,15 @@ +{ + "name": "files", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "esbuild src/plugin.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/plugin.js" + }, + "dependencies": { + "@rivethub/plugin-sdk": "0.7.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } +} diff --git a/plugins/files/rivethub-plugin.json b/plugins/files/rivethub-plugin.json new file mode 100644 index 0000000..6cae442 --- /dev/null +++ b/plugins/files/rivethub-plugin.json @@ -0,0 +1,19 @@ +{ + "manifest": 1, + "id": "files", + "name": "Files", + "version": "0.1.0", + "description": "Browse, upload, rename and delete files under one folder of this node, for the Files page and the workflow editor.", + "icon": "folder", + "run": { "command": ["node", "dist/plugin.js"] }, + "permissions": ["host.files.read", "host.files.write"], + "settings": [ + { + "key": "root", + "label": "Files root", + "input": { "type": "text" }, + "help": "The absolute folder the Files page and the workflow editor work in. Nothing outside it is reachable, through links either.", + "placeholder": "/srv/shared" + } + ] +} diff --git a/plugins/files/src/fence.ts b/plugins/files/src/fence.ts new file mode 100644 index 0000000..b9a914a --- /dev/null +++ b/plugins/files/src/fence.ts @@ -0,0 +1,95 @@ +import type { Stats } from 'node:fs' +import { lstat, realpath, stat } from 'node:fs/promises' +import { isAbsolute, join, relative, sep } from 'node:path' + +export class FilesError extends Error { + readonly status: number + + constructor(status: number, message: string) { + super(message) + this.status = status + } +} + +export const escaped = (): FilesError => new FilesError(403, 'path escapes the files root') + +export const failed = (what: string, error: unknown): FilesError => + new FilesError(500, `${what} failed: ${error instanceof Error ? error.message : String(error)}`) + +export const code = (error: unknown): string | undefined => + error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined + +export type Follow = 'target' | 'entry' +export type Final = 'mustExist' | 'mayBeNew' +export type Located = { absolute: string; relative: string } +export type Failures = { missing: FilesError; what: string } + +export function inside(root: string, path: string): boolean { + const rest = relative(root, path) + return rest === '' || (rest !== '..' && !rest.startsWith(`..${sep}`) && !isAbsolute(rest)) +} + +export async function openRoot(configured: string): Promise { + const unavailable = new FilesError(503, `files root not available: ${configured}`) + if (!isAbsolute(configured)) throw unavailable + try { + const root = await realpath(configured) + if ((await stat(root)).isDirectory()) return root + } catch (error) { + console.error(`[files] files root ${configured} is not available: ${String(error)}`) + } + throw unavailable +} + +function segments(raw: string): string[] { + if (raw.includes('\0') || raw.includes('\\') || raw.startsWith('/') || raw.startsWith('~')) throw escaped() + const parts = raw.split('/').filter((part) => part !== '' && part !== '.') + if (parts.includes('..')) throw escaped() + return parts +} + +async function linked(path: string, root: string, on: Failures): Promise { + try { + const target = await realpath(path) + if (inside(root, target)) return target + } catch (error) { + if (code(error) === 'ENOENT') throw on.missing + throw failed(on.what, error) + } + throw escaped() +} + +export async function locate(root: string, raw: string, follow: Follow, final: Final, on: Failures): Promise { + const parts = segments(raw) + let current = root + for (const [index, part] of parts.entries()) { + const last = index + 1 === parts.length + const next = join(current, part) + let found: Stats + try { + found = await lstat(next) + } catch (error) { + if (code(error) === 'ENOENT' && last && final === 'mayBeNew') { + current = next + continue + } + if (code(error) === 'ENOENT' || code(error) === 'ENOTDIR') throw on.missing + throw failed(on.what, error) + } + current = found.isSymbolicLink() && !(last && follow === 'entry') ? await linked(next, root, on) : next + } + if (!inside(root, current)) throw escaped() + return { absolute: current, relative: parts.join('/') } +} + +export async function shown(path: string, root: string): Promise { + const own = await lstat(path) + if (!own.isSymbolicLink()) return own + try { + const target = await realpath(path) + return inside(root, target) ? await stat(target) : own + } catch (error) { + if (code(error) === 'ENOENT') return own + throw error + } +} diff --git a/plugins/files/src/files.ts b/plugins/files/src/files.ts new file mode 100644 index 0000000..30d8e5e --- /dev/null +++ b/plugins/files/src/files.ts @@ -0,0 +1,294 @@ +import { constants } from 'node:fs' +import { link, lstat, mkdir, open, readdir, rename, rm, rmdir, stat, unlink } from 'node:fs/promises' +import { dirname, extname, join } from 'node:path' +import { Readable } from 'node:stream' +import type { Settings } from '@rivethub/plugin-sdk' +import { code, escaped, FilesError, failed, inside, type Located, locate, openRoot, shown } from './fence.ts' + +const GiB = 1024 * 1024 * 1024 +const INLINE: Record = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', + avif: 'image/avif', + ico: 'image/x-icon', + txt: 'text/plain; charset=utf-8', + md: 'text/plain; charset=utf-8', + log: 'text/plain; charset=utf-8', + xml: 'text/plain; charset=utf-8', + json: 'application/json', + csv: 'text/csv; charset=utf-8', + pdf: 'application/pdf', + mp3: 'audio/mpeg', + wav: 'audio/wav', + mp4: 'video/mp4', + webm: 'video/webm', +} + +type Entry = { name: string; type: 'dir' | 'file'; size: number; mtime: number } + +const answer = (body: unknown): Response => Response.json(body) +const changed = (path: string): Response => answer({ ok: true, path }) +const missing = (message: string): FilesError => new FilesError(404, message) +const joined = (dir: string, name: string): string => (dir === '' ? name : `${dir}/${name}`) +const upload = /^\..+\.part-\d+-\d+$/ + +function method(request: Request, expected: string): URLSearchParams { + if (request.method !== expected) throw new FilesError(405, 'method not allowed') + return new URL(request.url).searchParams +} + +function named(raw: string | null, kind: 'file' | 'directory'): string { + if (raw === null || raw === '' || raw === '.' || raw === '..' || /[/\\\0]/.test(raw)) { + throw new FilesError(422, `invalid ${kind} name`) + } + return raw +} + +function disposition(inline: boolean, name: string): string { + const kind = inline ? 'inline' : 'attachment' + if (/^[\x20-\x7e]+$/.test(name) && !/["\\]/.test(name)) return `${kind}; filename="${name}"` + const encoded = Array.from(Buffer.from(name, 'utf8')) + .map((byte) => { + const char = String.fromCharCode(byte) + return /[A-Za-z0-9\-_.~]/.test(char) ? char : `%${byte.toString(16).toUpperCase().padStart(2, '0')}` + }) + .join('') + return `${kind}; filename*=UTF-8''${encoded}` +} + +async function directory(located: Located): Promise { + const found = await stat(located.absolute).catch(() => undefined) + if (found?.isDirectory() !== true) throw missing('no such directory') +} + +async function absent(dest: string, overwrite: boolean): Promise { + const found = await lstat(dest).catch((error: unknown) => { + if (code(error) === 'ENOENT') return undefined + throw failed('upload', error) + }) + if (found?.isDirectory()) throw new FilesError(409, 'directory exists') + if (found !== undefined && !overwrite) throw new FilesError(409, 'file exists') +} + +async function written(temp: string, body: ReadableStream | null): Promise { + const handle = await open(temp, 'wx').catch(async (error: unknown) => { + if (code(error) !== 'EEXIST') throw failed('upload', error) + if ((await lstat(temp)).isSymbolicLink()) throw escaped() + throw new FilesError(500, 'upload failed: upload temp already exists') + }) + try { + let total = 0 + for await (const chunk of body ?? []) { + total += chunk.length + if (total > GiB) throw new FilesError(413, 'upload exceeds 1 GiB cap') + await handle.write(chunk) + } + await handle.sync() + } finally { + await handle.close() + } +} + +async function removed(path: string, recursive: boolean): Promise { + const found = await lstat(path) + if (!found.isDirectory()) return unlink(path) + if (recursive) return rm(path, { recursive: true }) + if ((await readdir(path)).length === 0) return rmdir(path) + throw new FilesError(409, 'directory not empty (pass recursive=1)') +} + +function respond(work: () => Promise): Promise { + return work().catch((error: unknown) => { + if (error instanceof FilesError) return Response.json({ error: error.message }, { status: error.status }) + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }) + }) +} + +export class Files { + #root: string | undefined + #seq = 0 + + configure(values: Settings): void { + const root = values.root + this.#root = typeof root === 'string' && root.trim() !== '' ? root.trim() : undefined + } + + #configured(): string { + if (this.#root === undefined) throw new FilesError(503, 'files browser disabled on this node') + return this.#root + } + + list(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'GET') + const root = await openRoot(configured) + const located = await locate(root, query.get('path') ?? '', 'target', 'mustExist', { + missing: missing('no such directory'), + what: 'list', + }) + await directory(located) + const entries: Entry[] = [] + try { + for (const name of await readdir(located.absolute)) { + if (upload.test(name)) continue + const found = await shown(join(located.absolute, name), root) + entries.push({ + name, + type: found.isDirectory() ? 'dir' : 'file', + size: found.size, + mtime: Math.trunc(found.mtimeMs), + }) + } + } catch (error) { + throw failed('list', error) + } + entries.sort((a, b) => + a.type !== b.type ? (a.type === 'dir' ? -1 : 1) : a.name < b.name ? -1 : a.name > b.name ? 1 : 0, + ) + return answer({ path: located.relative, root, entries }) + }) + } + + download(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'GET') + const root = await openRoot(configured) + const located = await locate(root, query.get('path') ?? '', 'target', 'mustExist', { + missing: missing('no such file'), + what: 'download', + }) + const handle = await open( + located.absolute, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ).catch((error: unknown) => { + if (code(error) === 'ENOENT') throw missing('no such file') + if (code(error) === 'ELOOP') throw escaped() + throw failed('download', error) + }) + const found = await handle.stat() + if (!found.isFile() || found.size > GiB) { + await handle.close() + throw found.isFile() ? new FilesError(413, 'download exceeds 1 GiB cap') : missing('no such file') + } + const name = located.relative.split('/').at(-1) ?? '' + const type = INLINE[extname(name).slice(1).toLowerCase()] + return new Response(Readable.toWeb(handle.createReadStream()) as ReadableStream, { + headers: { + 'content-type': type ?? 'application/octet-stream', + 'content-disposition': disposition(type !== undefined, name), + 'x-content-type-options': 'nosniff', + }, + }) + }) + } + + upload(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'POST') + const name = named(query.get('name'), 'file') + const overwrite = query.get('overwrite') === '1' + const root = await openRoot(configured) + const parent = await locate(root, query.get('dir') ?? '', 'target', 'mustExist', { + missing: missing('no such directory'), + what: 'upload', + }) + await directory(parent) + const dest = join(parent.absolute, name) + const temp = join(parent.absolute, `.${name}.part-${process.pid}-${++this.#seq}`) + if (!inside(root, dest) || !inside(root, temp)) throw escaped() + await absent(dest, overwrite) + try { + await written(temp, request.body) + await absent(dest, overwrite) + if (overwrite) { + await rename(temp, dest).catch((error: unknown) => { + throw failed('upload', error) + }) + } else { + await link(temp, dest).catch((error: unknown) => { + throw code(error) === 'EEXIST' ? new FilesError(409, 'file exists') : failed('upload', error) + }) + } + } finally { + await rm(temp, { force: true }) + } + return changed(joined(parent.relative, name)) + }) + } + + mkdir(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'POST') + const name = named(query.get('name'), 'directory') + const root = await openRoot(configured) + const parent = await locate(root, query.get('dir') ?? '', 'target', 'mustExist', { + missing: missing('no such directory'), + what: 'mkdir', + }) + await directory(parent) + await mkdir(join(parent.absolute, name)).catch((error: unknown) => { + throw code(error) === 'EEXIST' ? new FilesError(409, 'directory exists') : failed('mkdir', error) + }) + return changed(joined(parent.relative, name)) + }) + } + + rename(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'POST') + const from = query.get('from') + const to = query.get('to') + if (!from || !to) throw new FilesError(422, 'from and to are required') + const root = await openRoot(configured) + const source = await locate(root, from, 'entry', 'mustExist', { + missing: missing('no such path'), + what: 'rename', + }) + const destinationMissing = missing('destination directory does not exist') + const dest = await locate(root, to, 'entry', 'mayBeNew', { missing: destinationMissing, what: 'rename' }) + if (source.relative === dest.relative) throw new FilesError(422, 'from and to are the same path') + if (source.relative === '' || dest.relative === '') throw new FilesError(403, 'cannot rename the files root') + if ((await shown(source.absolute, root)).isDirectory() && inside(source.absolute, dest.absolute)) { + throw new FilesError(422, 'cannot move a directory into itself') + } + const parent = dirname(dest.absolute) + if (!inside(root, parent) || !(await stat(parent).catch(() => undefined))?.isDirectory()) { + throw destinationMissing + } + if ((await lstat(dest.absolute).catch(() => undefined))?.isDirectory()) { + throw new FilesError(409, 'directory exists') + } + await rename(source.absolute, dest.absolute).catch((error: unknown) => { + throw failed('rename', error) + }) + return changed(dest.relative) + }) + } + + delete(request: Request): Promise { + return respond(async () => { + const configured = this.#configured() + const query = method(request, 'DELETE') + const raw = query.get('path') + if (!raw) throw new FilesError(422, 'path is required') + const root = await openRoot(configured) + const located = await locate(root, raw, 'entry', 'mustExist', { + missing: missing('no such path'), + what: 'delete', + }) + if (located.relative === '') throw new FilesError(403, 'cannot delete the files root') + await removed(located.absolute, query.get('recursive') === '1').catch((error: unknown) => { + throw error instanceof FilesError ? error : failed('delete', error) + }) + return changed(located.relative) + }) + } +} diff --git a/plugins/files/src/plugin.ts b/plugins/files/src/plugin.ts new file mode 100644 index 0000000..6b8ea58 --- /dev/null +++ b/plugins/files/src/plugin.ts @@ -0,0 +1,16 @@ +import { serve } from '@rivethub/plugin-sdk' +import { Files } from './files.ts' + +const files = new Files() + +await serve({ + http: { + list: (request) => files.list(request), + download: (request) => files.download(request), + upload: (request) => files.upload(request), + mkdir: (request) => files.mkdir(request), + rename: (request) => files.rename(request), + delete: (request) => files.delete(request), + }, + settings: (values) => files.configure(values), +}) diff --git a/plugins/voice/package.json b/plugins/voice/package.json new file mode 100644 index 0000000..c36690b --- /dev/null +++ b/plugins/voice/package.json @@ -0,0 +1,15 @@ +{ + "name": "voice", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "esbuild src/plugin.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/plugin.js" + }, + "dependencies": { + "@rivethub/plugin-sdk": "0.7.0" + }, + "devDependencies": { + "esbuild": "0.28.2" + } +} diff --git a/plugins/voice/rivethub-plugin.json b/plugins/voice/rivethub-plugin.json new file mode 100644 index 0000000..0c90725 --- /dev/null +++ b/plugins/voice/rivethub-plugin.json @@ -0,0 +1,32 @@ +{ + "manifest": 1, + "id": "voice", + "name": "Voice", + "version": "0.1.0", + "description": "Speech to text and text to speech for the composer, through the STT and TTS servers this node is set up with.", + "icon": "mic", + "run": { "command": ["node", "dist/plugin.js"] }, + "permissions": ["host.network"], + "settings": [ + { + "key": "sttUrl", + "label": "Transcription URL", + "input": { "type": "text" }, + "help": "An OpenAI-compatible transcription endpoint that takes a multipart file and answers {text}.", + "placeholder": "https://stt.example.com/v1/audio/transcriptions" + }, + { + "key": "ttsUrl", + "label": "Speech URL", + "input": { "type": "text" }, + "help": "An OpenAI-compatible speech endpoint that takes {input, response_format, instructions?, voice?}.", + "placeholder": "https://tts.example.com/v1/audio/speech" + }, + { + "key": "instructions", + "label": "Speaking instructions", + "input": { "type": "text", "multiline": true }, + "help": "Sent with each request that brings none of its own." + } + ] +} diff --git a/plugins/voice/src/plugin.ts b/plugins/voice/src/plugin.ts new file mode 100644 index 0000000..1d4b44d --- /dev/null +++ b/plugins/voice/src/plugin.ts @@ -0,0 +1,12 @@ +import { serve } from '@rivethub/plugin-sdk' +import { Voice } from './voice.ts' + +const voice = new Voice() + +await serve({ + http: { + transcribe: (request) => voice.transcribe(request), + speak: (request) => voice.speak(request), + }, + settings: (values) => voice.configure(values), +}) diff --git a/plugins/voice/src/voice.ts b/plugins/voice/src/voice.ts new file mode 100644 index 0000000..1757cb6 --- /dev/null +++ b/plugins/voice/src/voice.ts @@ -0,0 +1,267 @@ +import type { Settings } from '@rivethub/plugin-sdk' + +const MiB = 1024 * 1024 +const AUDIO_LIMIT = 15 * MiB +const SPEAK_LIMIT = 64 * 1024 +const INPUT_LIMIT = 4096 +const TRANSCRIPT_LIMIT = MiB +const SPEECH_LIMIT = 30 * MiB +const SNIPPET_CHARS = 240 +const SNIPPET_BYTES = 8 * 1024 +const STT_TIMEOUT_MS = 60_000 +const TTS_TIMEOUT_MS = 120_000 +const WAV = 'audio/wav' +const MEDIA = new Set([ + 'audio/wav', + 'audio/wave', + 'audio/x-wav', + 'audio/mpeg', + 'audio/mp3', + 'audio/mp4', + 'audio/m4a', + 'audio/x-m4a', + 'audio/aac', + 'audio/webm', + 'audio/ogg', + 'audio/flac', + 'application/octet-stream', + 'video/webm', +]) + +class VoiceError extends Error { + readonly status: number + + constructor(status: number, message: string) { + super(message) + this.status = status + } +} + +type Endpoint = { url: URL } | { fault: string } | undefined +type Endpoints = { stt: Endpoint; tts: Endpoint; instructions: string | undefined } + +const text = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined + +function endpoint(raw: unknown, kind: string): Endpoint { + const value = text(raw) + if (value === undefined) return undefined + const url = URL.parse(value) + if (url === null || (url.protocol !== 'http:' && url.protocol !== 'https:') || url.hostname === '') { + return { fault: `voice ${kind} URL is invalid: ${value} must be an http or https URL with a host` } + } + return { url } +} + +const answer = (status: number, body: unknown): Response => Response.json(body, { status }) + +function failure(error: unknown): Response { + if (error instanceof VoiceError) return answer(error.status, { error: error.message }) + return answer(500, { error: error instanceof Error ? error.message : String(error) }) +} + +function snippet(bytes: Uint8Array): string { + if (bytes.length === 0) return 'upstream body was empty' + return Array.from(new TextDecoder().decode(bytes)).slice(0, SNIPPET_CHARS).join('') +} + +function upstream(route: string, detail: string): VoiceError { + console.error(`[voice] ${route} upstream failed: ${detail}`) + return new VoiceError(502, `voice upstream failed: ${detail}`) +} + +const status = (response: Response): string => `status ${response.status} ${response.statusText}`.trimEnd() + +function cause(error: unknown): string { + const parts: string[] = [] + let current: unknown = error + while (current instanceof Error && parts.length < 8) { + parts.push(current.message) + current = current.cause + } + return Array.from(parts.join(': ')).slice(0, SNIPPET_CHARS).join('') +} + +async function read(body: ReadableStream | null, limit: number): Promise { + if (body === null) return new Uint8Array() + const reader = body.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + try { + for (let next = await reader.read(); !next.done; next = await reader.read()) { + size += next.value.length + if (size > limit) throw new RangeError() + chunks.push(next.value) + } + } finally { + reader.releaseLock() + } + return Buffer.concat(chunks) +} + +async function prefix(response: Response): Promise { + const chunks: Uint8Array[] = [] + let size = 0 + try { + for await (const chunk of response.body ?? []) { + chunks.push(chunk.subarray(0, SNIPPET_BYTES - size)) + size += chunk.length + if (size >= SNIPPET_BYTES) break + } + } catch {} + return Buffer.concat(chunks) +} + +function media(header: string | null): string { + const named = header?.split(';')[0]?.trim().toLowerCase() ?? '' + return MEDIA.has(named) ? named : WAV +} + +function capped(body: ReadableStream): ReadableStream { + let seen = 0 + return body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + seen += chunk.length + if (seen > SPEECH_LIMIT) controller.error(new Error('upstream audio exceeds 30 MiB')) + else controller.enqueue(chunk) + }, + }), + ) +} + +type Speak = { input: string; instructions?: string; voice?: string } + +function speakBody(bytes: Uint8Array): Speak { + let document: unknown + try { + document = JSON.parse(new TextDecoder().decode(bytes)) + } catch { + throw new VoiceError(400, 'speak body must be JSON') + } + if (typeof document !== 'object' || document === null || Array.isArray(document)) { + throw new VoiceError(400, 'speak body must be a JSON object') + } + const { input, instructions, voice } = document as Record + for (const [key, value] of Object.entries({ input, instructions, voice })) { + if (value !== undefined && value !== null && typeof value !== 'string') { + throw new VoiceError(400, `${key} must be a string`) + } + } + if (typeof input !== 'string' || input === '') throw new VoiceError(400, 'input required') + if (Buffer.byteLength(input) > INPUT_LIMIT) throw new VoiceError(400, 'input exceeds 4096 UTF-8 bytes') + return { + input, + ...(typeof instructions === 'string' ? { instructions } : {}), + ...(typeof voice === 'string' ? { voice } : {}), + } +} + +export class Voice { + #endpoints: Endpoints = { stt: undefined, tts: undefined, instructions: undefined } + + configure(values: Settings): void { + this.#endpoints = { + stt: endpoint(values.sttUrl, 'transcription'), + tts: endpoint(values.ttsUrl, 'synthesis'), + instructions: text(values.instructions), + } + for (const found of [this.#endpoints.stt, this.#endpoints.tts]) { + if (found !== undefined && 'fault' in found) console.error(`[voice] ${found.fault}`) + } + } + + #configured(kind: 'stt' | 'tts'): URL { + const found = this.#endpoints[kind] + if (found === undefined) { + throw new VoiceError( + 501, + `voice ${kind === 'stt' ? 'transcription' : 'synthesis'} is not configured on this node`, + ) + } + if ('fault' in found) throw new VoiceError(501, found.fault) + return found.url + } + + async transcribe(request: Request): Promise { + if (request.method !== 'POST') return answer(404, { error: 'not found' }) + try { + const url = this.#configured('stt') + const audio = await read(request.body, AUDIO_LIMIT).catch((error: unknown) => { + if (error instanceof RangeError) throw new VoiceError(413, 'audio body too large') + throw new VoiceError(400, `the voice request body failed: ${cause(error)}`) + }) + if (audio.length === 0) throw new VoiceError(400, 'empty audio body') + const form = new FormData() + form.append('file', new Blob([audio], { type: media(request.headers.get('content-type')) }), 'speech.audio') + const response = await fetch(url, { + method: 'POST', + body: form, + signal: AbortSignal.timeout(STT_TIMEOUT_MS), + }).catch((error: unknown) => { + throw upstream('transcribe', cause(error)) + }) + if (!response.ok) { + throw upstream('transcribe', `${status(response)}: ${snippet(await prefix(response))}`) + } + const body = await read(response.body, TRANSCRIPT_LIMIT).catch(async (error: unknown) => { + await response.body?.cancel().catch(() => undefined) + throw upstream( + 'transcribe', + error instanceof RangeError ? 'upstream transcription exceeds 1 MiB' : cause(error), + ) + }) + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder().decode(body)) + } catch { + throw upstream('transcribe', snippet(body)) + } + const transcript = (parsed as { text?: unknown } | null)?.text + if (typeof transcript !== 'string') throw upstream('transcribe', snippet(body)) + return answer(200, { text: transcript }) + } catch (error) { + return failure(error) + } + } + + async speak(request: Request): Promise { + if (request.method !== 'POST') return answer(404, { error: 'not found' }) + try { + const url = this.#configured('tts') + const bytes = await read(request.body, SPEAK_LIMIT).catch((error: unknown) => { + if (error instanceof RangeError) throw new VoiceError(400, 'speak body too large') + throw new VoiceError(400, `the voice request body failed: ${cause(error)}`) + }) + const body = speakBody(bytes) + const instructions = body.instructions ?? this.#endpoints.instructions + const response = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + input: body.input, + response_format: 'wav', + ...(instructions === undefined ? {} : { instructions }), + ...(body.voice === undefined ? {} : { voice: body.voice }), + }), + signal: AbortSignal.timeout(TTS_TIMEOUT_MS), + }).catch((error: unknown) => { + throw upstream('speak', cause(error)) + }) + if (!response.ok) { + throw upstream('speak', `${status(response)}: ${snippet(await prefix(response))}`) + } + if (Number(response.headers.get('content-length') ?? 0) > SPEECH_LIMIT) { + await response.body?.cancel() + throw upstream('speak', 'upstream audio exceeds 30 MiB') + } + const type = response.headers.get('content-type') || WAV + return new Response(response.body === null ? null : capped(response.body), { + status: 200, + headers: { 'content-type': type }, + }) + } catch (error) { + return failure(error) + } + } +} diff --git a/tests/files.test.ts b/tests/files.test.ts new file mode 100644 index 0000000..6c5a61e --- /dev/null +++ b/tests/files.test.ts @@ -0,0 +1,102 @@ +import assert from 'node:assert/strict' +import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { after, test } from 'node:test' +import { Files } from '../plugins/files/src/files.ts' + +const scratch = await realpath(await mkdtemp(join(tmpdir(), 'files-plugin-'))) +after(() => rm(scratch, { recursive: true, force: true })) + +let trees = 0 + +async function tree(): Promise<{ files: Files; root: string; outside: string }> { + const base = join(scratch, String(++trees)) + const root = join(base, 'root') + const outside = join(base, 'outside') + await mkdir(join(root, 'nested'), { recursive: true }) + await mkdir(outside) + await writeFile(join(root, 'nested', 'leaf.txt'), 'leaf') + await writeFile(join(outside, 'secret'), 'SECRET') + await symlink(join(outside, 'secret'), join(root, 'out')) + await symlink(outside, join(root, 'outdir')) + await symlink(join(root, 'nested'), join(root, 'aliasdir')) + const files = new Files() + files.configure({ root }) + return { files, root, outside } +} + +const call = (method: string, route: string, body?: string): Request => + new Request(`http://plugin/http/${route}`, { method, ...(body === undefined ? {} : { body }) }) + +async function refused(response: Response, status: number, error: string): Promise { + assert.equal(response.status, status) + assert.deepEqual(await response.json(), { error }) +} + +test('no path climbs out of the root, plain or percent-encoded', async () => { + const { files } = await tree() + for (const encoded of [ + '..', + 'nested/../..', + '%2Fetc%2Fpasswd', + '~%2Fx', + 'a%5Cb', + '%2e%2e', + '..%2F..%2Fsecret', + '%2e%2e%2fsecret', + ]) { + const query = `path=${encoded}` + await refused(await files.download(call('GET', `download?${query}`)), 403, 'path escapes the files root') + await refused(await files.list(call('GET', `list?${query}`)), 403, 'path escapes the files root') + await refused(await files.delete(call('DELETE', `delete?${query}`)), 403, 'path escapes the files root') + } + await refused(await files.upload(call('POST', 'upload?dir=..&name=x', 'x')), 403, 'path escapes the files root') + await refused(await files.rename(call('POST', 'rename?from=nested&to=../moved')), 403, 'path escapes the files root') +}) + +test('links are followed only while they stay inside the root', async () => { + const { files, outside } = await tree() + await refused(await files.download(call('GET', 'download?path=out')), 403, 'path escapes the files root') + await refused(await files.list(call('GET', 'list?path=outdir')), 403, 'path escapes the files root') + await refused( + await files.upload(call('POST', 'upload?dir=outdir&name=planted', 'x')), + 403, + 'path escapes the files root', + ) + const aliased = await files.download(call('GET', 'download?path=aliasdir/leaf.txt')) + assert.equal(aliased.status, 200) + assert.equal(await aliased.text(), 'leaf') + const listed = (await (await files.list(call('GET', 'list'))).json()) as { entries: { name: string; type: string }[] } + assert.deepEqual( + listed.entries.map(({ name, type }) => `${type}:${name}`), + ['dir:aliasdir', 'dir:nested', 'file:out', 'file:outdir'], + ) + assert.equal((await files.delete(call('DELETE', 'delete?path=outdir'))).status, 200) + assert.equal((await files.delete(call('DELETE', 'delete?path=out'))).status, 200) + assert.equal(await readFile(join(outside, 'secret'), 'utf8'), 'SECRET') +}) + +test('uploads land whole under their name, never clobber unasked, and hide their part file', async () => { + const { files, root } = await tree() + const first = await files.upload(call('POST', 'upload?dir=nested&name=new.txt', 'one')) + assert.deepEqual(await first.json(), { ok: true, path: 'nested/new.txt' }) + await refused(await files.upload(call('POST', 'upload?dir=nested&name=new.txt', 'two')), 409, 'file exists') + assert.equal((await files.upload(call('POST', 'upload?dir=nested&name=new.txt&overwrite=1', 'two'))).status, 200) + assert.equal(await readFile(join(root, 'nested', 'new.txt'), 'utf8'), 'two') + await refused(await files.upload(call('POST', 'upload?dir=nested&name=..', 'x')), 422, 'invalid file name') + await writeFile(join(root, 'nested', '.new.txt.part-1-2'), 'partial') + const listed = (await (await files.list(call('GET', 'list?path=nested'))).json()) as { entries: { name: string }[] } + assert.deepEqual( + listed.entries.map(({ name }) => name), + ['leaf.txt', 'new.txt'], + ) +}) + +test('a node without a root answers that the browser is disabled', async () => { + const files = new Files() + files.configure({}) + await refused(await files.list(call('GET', 'list')), 503, 'files browser disabled on this node') + files.configure({ root: 'relative/root' }) + await refused(await files.list(call('GET', 'list')), 503, 'files root not available: relative/root') +}) diff --git a/tsconfig.json b/tsconfig.json index e858d8b..d2be8af 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,5 +17,5 @@ "noEmit": true, "skipLibCheck": true }, - "include": ["scripts", "tests", "packages/*/src", "templates/typescript/src"] + "include": ["scripts", "tests", "packages/*/src", "templates/typescript/src", "plugins/*/src"] }