Open History to see the last commit
1import {
2 GUEST_MESSAGE_MAX_ATTACHMENT_BYTES,
3 GUEST_MESSAGE_MAX_ATTACHMENTS,
4 isProviderSendTurnSupportedImageMimeType,
5} from "@t3tools/contracts";
6import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
7import { markdownDestinationHostPath } from "@t3tools/shared/markdownLinks";
8import { chatMarkdownImageSources } from "@t3tools/shared/markdownPipeline";
9import { isAbsolutePath, isNetworkPath } from "@t3tools/shared/path";
10
11/** A file from a guest's message request, saved by the multipart parser to a temporary path. */
12export interface GuestUpload {
13 readonly name: string;
14 readonly contentType: string;
15 readonly path: string;
16}
17
18/** What the server learned about an upload before deciding what it may become. */
19export interface InspectedGuestUpload {
20 readonly name: string;
21 readonly contentType: string;
22 readonly sizeBytes: number;
23 /** The first bytes of the file. */
24 readonly header: Uint8Array;
25}
26
27export type GuestUploadRejection = "too_many_files" | "too_large" | "unsupported_file";
28
29/** An attachment before it is stored and gets its id. */
30export interface GuestAttachmentDraft {
31 readonly type: "image" | "file";
32 readonly name: string;
33 readonly mimeType: string;
34 readonly sizeBytes: number;
35}
36
37/** Bytes of the file the signature check reads. */
38export const GUEST_UPLOAD_HEADER_BYTES = 12;
39
40const startsWith = (header: Uint8Array, bytes: ReadonlyArray<number>, offset = 0) =>
41 bytes.every((byte, index) => header[offset + index] === byte);
42const ascii = (text: string) => Array.from(text, (character) => character.charCodeAt(0));
43
44/** An image must be what its type says, so a renamed HTML page never travels as one. */
45const IMAGE_SIGNATURES: Readonly<Record<string, (header: Uint8Array) => boolean>> = {
46 "image/png": (header) => startsWith(header, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
47 "image/jpeg": (header) => startsWith(header, [0xff, 0xd8, 0xff]),
48 "image/gif": (header) => startsWith(header, ascii("GIF8")),
49 "image/webp": (header) =>
50 startsWith(header, ascii("RIFF")) && startsWith(header, ascii("WEBP"), 8),
51};
52
53export const matchesImageSignature = (mimeType: string, header: Uint8Array) =>
54 IMAGE_SIGNATURES[mimeType]?.(header) === true;
55
56const IMAGE_TYPE_BY_EXTENSION: ReadonlyMap<string, string> = new Map([
57 ["png", "image/png"],
58 ["jpg", "image/jpeg"],
59 ["jpeg", "image/jpeg"],
60 ["gif", "image/gif"],
61 ["webp", "image/webp"],
62]);
63
64/**
65 * The type of a host image a guest may ask for by path, or null. A network path never qualifies:
66 * it would make the host reach out to another machine.
67 */
68export function guestHostImageType(path: string): string | null {
69 if (!isAbsolutePath(path) || isNetworkPath(path)) return null;
70 return IMAGE_TYPE_BY_EXTENSION.get(path.split(".").at(-1)!.toLowerCase()) ?? null;
71}
72
73/**
74 * Whether an agent reply shows the image at `path`, so the guest already sees it. `imageSources`
75 * lets the caller reuse a reply's parse across requests.
76 */
77export function repliesShowImage<Reply extends { readonly text: string }>(
78 path: string,
79 replies: ReadonlyArray<Reply>,
80 imageSources: (reply: Reply) => ReadonlyArray<string> = (reply) =>
81 chatMarkdownImageSources(reply.text),
82) {
83 // Parsing is the slow part; a reply with no image syntax shows no image.
84 return replies.some(
85 (reply) =>
86 (reply.text.includes("![") || /<img/i.test(reply.text)) &&
87 imageSources(reply).some((source) => markdownDestinationHostPath(source) === path),
88 );
89}
90
91/**
92 * Control characters and separators would break the name in headers and on disk, and direction
93 * overrides would let `invoice\u202Efdp.exe` show as a PDF.
94 */
95const safeName = (name: string, fallback: string) => {
96 const cleaned = name
97 .replace(/[\p{Cc}\\/\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu, "_")
98 .trim();
99 return cleaned.slice(0, splitsSurrogatePair(cleaned, 255) ? 254 : 255) || fallback;
100};
101
102/**
103 * The attachments a guest's files become, as the owner's composer takes them: supported images as
104 * images, anything else that is not an image as a file. Other image types (SVG, HEIC) and empty
105 * files are refused, as are too many files or too many bytes in one message.
106 */
107export function classifyGuestUploads(
108 uploads: ReadonlyArray<InspectedGuestUpload>,
109):
110 | { readonly ok: true; readonly attachments: ReadonlyArray<GuestAttachmentDraft> }
111 | { readonly ok: false; readonly reason: GuestUploadRejection } {
112 if (uploads.length > GUEST_MESSAGE_MAX_ATTACHMENTS)
113 return { ok: false, reason: "too_many_files" };
114 const total = uploads.reduce((sum, upload) => sum + upload.sizeBytes, 0);
115 if (total > GUEST_MESSAGE_MAX_ATTACHMENT_BYTES) return { ok: false, reason: "too_large" };
116 const attachments: Array<GuestAttachmentDraft> = [];
117 for (const upload of uploads) {
118 const mimeType =
119 upload.contentType.split(";", 1)[0]!.trim().toLowerCase() || "application/octet-stream";
120 if (upload.sizeBytes === 0) return { ok: false, reason: "unsupported_file" };
121 if (mimeType.startsWith("image/")) {
122 if (
123 !isProviderSendTurnSupportedImageMimeType(mimeType) ||
124 !matchesImageSignature(mimeType, upload.header)
125 ) {
126 return { ok: false, reason: "unsupported_file" };
127 }
128 attachments.push({
129 type: "image",
130 name: safeName(upload.name, "image"),
131 mimeType,
132 sizeBytes: upload.sizeBytes,
133 });
134 continue;
135 }
136 attachments.push({
137 type: "file",
138 name: safeName(upload.name, "file"),
139 mimeType: mimeType.length <= 100 ? mimeType : "application/octet-stream",
140 sizeBytes: upload.sizeBytes,
141 });
142 }
143 return { ok: true, attachments };
144}