Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

inline-media.ts

239 lines8.5 KB

1// The checks on media that a client sends inside an input. Inline bytes go
2// to the media store, so the transcript, the log, and every viewer get a
3// small `harness-media:` reference. External URLs are refused unless the
4// harness allows them.
5import { MEDIA_URL_PREFIX, kindOf, mediaPart } from './media-ref'
6import { MediaError } from './media'
7import type { ContentPart } from '@tanstack/ai'
8import type { MediaOptions } from './media'
9import type { MediaRecord, MediaUpload } from './types'
10​
11/** The default of `media.maxBodyBytes`: 32 MiB. */
12export const DEFAULT_MAX_BODY_BYTES = 32 * 1024 * 1024
13​
14/**
15 * Why a client content part was refused. It is the `reason` of the receipt.
16 *
17 * - `media_too_large`: the bytes are over `media.maxBytes`.
18 * - `media_not_allowed`: a MIME type with no media kind, or a kind not in
19 * `media.kinds`.
20 * - `media_invalid`: the data is not base64.
21 * - `media_url_not_allowed`: a URL that `media.externalUrls` refuses, a
22 * URL scheme other than `http:`, `https:`, `data:`, and `harness-media:`,
23 * or a provider file handle without `media.allowProviderFiles`.
24 */
25export type InlineMediaRefusal =
26 | 'media_too_large'
27 | 'media_not_allowed'
28 | 'media_invalid'
29 | 'media_url_not_allowed'
30​
31/** What `storeInlineMedia` needs: the media options and a store. */
32export interface InlineMediaContext {
33 options: MediaOptions | undefined
34 /** Store the bytes, as `session.putMedia` does. */
35 putMedia: (upload: MediaUpload<Uint8Array>) => Promise<MediaRecord>
37​
38type MediaContentPart = Exclude<ContentPart, { type: 'text' }>
39​
40/** A checked part, with the bytes that it must store, if any. */
41type CheckedPart =
42 | { part: ContentPart; upload?: undefined }
43 | { part: MediaContentPart; upload: MediaUpload<Uint8Array> }
44​
45const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/
46// `data:<type>[;params];base64,<data>`. Only base64 data URLs carry bytes.
47const DATA_URL = /^data:([^,]*?);base64,(.*)$/s
48​
49/** A refused part. `reason` goes to the receipt. */
50function refuse(reason: InlineMediaRefusal) {
51 return { refused: reason }
53​
54/** The bytes of base64 `value`, or `undefined` when it is not base64. */
55function fromBase64(value: string) {
56 const clean = value.replace(/\s/g, '')
57 if (clean.length % 4 === 1 || !BASE64.test(clean)) return undefined
58 const NodeBuffer = globalThis.Buffer
59 if (typeof NodeBuffer === 'function') {
60 return new Uint8Array(NodeBuffer.from(clean, 'base64'))
61 }
62 return Uint8Array.from(atob(clean), (char) => char.charCodeAt(0))
64​
65/** The number of bytes that base64 `value` holds, without decoding it. */
66function base64Size(value: string) {
67 const clean = value.replace(/\s/g, '')
68 const padding = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0
69 return Math.floor((clean.length * 3) / 4) - padding
71​
72/** True when `media.externalUrls` lets a part point to `url`. */
73function isUrlAllowed(url: URL, options: MediaOptions | undefined) {
74 const isWeb = url.protocol === 'http:' || url.protocol === 'https:'
75 if (!isWeb) return false
76 const allow = options?.externalUrls ?? false
77 return typeof allow === 'function' ? allow(url) : allow
79​
80/** `part`, checked, with the bytes it must store, or why it was refused. */
81function checkBytes(
82 part: MediaContentPart,
83 data: { value: string; mimeType: string },
84 options: MediaOptions | undefined,
85) {
86 const kind = kindOf(data.mimeType)
87 const isKindAllowed =
88 kind !== undefined && (options?.kinds ?? [kind]).includes(kind)
89 if (!isKindAllowed) return refuse('media_not_allowed')
90 const isTooLarge =
91 options?.maxBytes !== undefined && base64Size(data.value) > options.maxBytes
92 if (isTooLarge) return refuse('media_too_large')
93 const bytes = fromBase64(data.value)
94 if (bytes === undefined) return refuse('media_invalid')
95 const checked: CheckedPart = {
96 part,
97 upload: { body: bytes, mimeType: data.mimeType, name: kind },
98 }
99 return checked
101​
102/** One part, checked, or the reason it was refused. Stores nothing. */
103function checkPart(
104 part: ContentPart,
105 options: MediaOptions | undefined,
106): CheckedPart | { refused: InlineMediaRefusal } {
107 if (part.type === 'text') return { part }
108 const { source } = part
109 if (source.type === 'data') return checkBytes(part, source, options)
110 // A provider file handle is read with the server's provider key.
111 if (source.type === 'file') {
112 return options?.allowProviderFiles === true
113 ? { part }
114 : refuse('media_url_not_allowed')
115 }
116 if (source.value.startsWith(MEDIA_URL_PREFIX)) return { part }
117 const dataUrl = DATA_URL.exec(source.value)
118 if (dataUrl) {
119 const [, mimeType = '', value = ''] = dataUrl
120 return checkBytes(part, { value, mimeType }, options)
121 }
122 const url = URL.canParse(source.value) ? new URL(source.value) : undefined
123 if (url === undefined || !isUrlAllowed(url, options)) {
124 return refuse('media_url_not_allowed')
125 }
126 return { part }
128​
129/**
130 * Check the content parts that a client sent, at the trust boundary. Inline
131 * bytes (a `data` source, or a base64 `data:` URL) go to the media store
132 * with `putMedia`, and the part becomes a `harness-media:` reference. So the
133 * bytes are checked against `media.kinds` and `media.maxBytes`, and the model
134 * check of `harness-media:` parts runs on them. An `http:` or `https:` URL
135 * stays only when `media.externalUrls` allows it. A provider file handle
136 * stays only when `media.allowProviderFiles` is `true`. Other URL schemes are
137 * refused. Text and `harness-media:` parts stay as they are.
138 *
139 * Resolves to `{ parts }`, or to `{ refused }` with the reason of the first
140 * part that was refused. Every part is checked before any part is stored, so
141 * a refused input stores nothing.
142 *
143 * @example
144 * ```ts
145 * const checked = await storeInlineMedia(parts, {
146 * options: harness.media,
147 * putMedia: (upload) => session.putMedia(upload),
148 * })
149 * if ('refused' in checked) return reject(checked.refused)
150 * session.send(checked.parts)
151 * ```
152 */
153export async function storeInlineMedia(
154 parts: ReadonlyArray<ContentPart>,
155 context: InlineMediaContext,
156) {
157 const pending: Array<CheckedPart> = []
158 for (const part of parts) {
159 const result = checkPart(part, context.options)
160 if ('refused' in result) return result
161 pending.push(result)
162 }
163 const checked: Array<ContentPart> = []
164 for (const entry of pending) {
165 if (entry.upload === undefined) {
166 checked.push(entry.part)
167 continue
168 }
169 try {
170 const record = await context.putMedia(entry.upload)
171 // Other fields, like provider metadata, stay on the part.
172 const stored: ContentPart = { ...entry.part, ...mediaPart(record) }
173 checked.push(stored)
174 } catch (error) {
175 // ponytail: the store refuses only what the checks above let through
176 // when its own limits differ (its 100 MB default `maxBytes`). Parts
177 // stored before such a refusal stay in the store.
178 if (!(error instanceof MediaError)) throw error
179 return refuse(
180 error.status === 413 ? 'media_too_large' : 'media_not_allowed',
181 )
182 }
183 }
184 return { parts: checked }
186​
187/**
188 * The largest request body or socket frame, in bytes, that a transport
189 * reads: `media.maxBodyBytes`, or 32 MiB. A socket checks a frame after the
190 * WebSocket server read it, so this saves only the parse.
191 *
192 * @example
193 * ```ts
194 * if (frame.length > maxBodyBytesOf(harness.media)) socket.close(1009)
195 * ```
196 */
197export function maxBodyBytesOf(options: MediaOptions | undefined) {
198 return options?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES
200​
201/**
202 * The body of `request` as text, read up to `media.maxBodyBytes`. Throws a
203 * `MediaError` with 413 when the `Content-Length` or the bytes read are over
204 * the limit. It stops reading at the limit, so a large body is not buffered.
205 *
206 * @example
207 * ```ts
208 * const body: unknown = JSON.parse(await readBodyText(request, harness.media))
209 * ```
210 */
211export async function readBodyText(
212 request: Request,
213 options: MediaOptions | undefined,
214) {
215 const limit = maxBodyBytesOf(options)
216 const tooLarge = () =>
217 new MediaError(413, `The body is bigger than the limit of ${limit} bytes.`)
218 const declared = Number(request.headers.get('content-length') ?? 0)
219 if (declared > limit) throw tooLarge()
220 if (request.body === null) return ''
221 const reader = request.body.getReader()
222 const chunks: Array<Uint8Array> = []
223 let size = 0
224 for (;;) {
225 const { done, value } = await reader.read()
226 if (done) break
227 size += value.byteLength
228 if (size > limit) {
229 await reader.cancel()
230 throw tooLarge()
231 }
232 chunks.push(value)
233 }
234 const decoder = new TextDecoder()
235 return (
236 chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join('') +
237 decoder.decode()
238 )