Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5
6import type { ChatAttachment } from "@t3tools/contracts";
7
8import {
9 normalizeAttachmentRelativePath,
10 resolveAttachmentRelativePath,
11} from "./attachmentPaths.ts";
12import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
13
14const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
15const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
16const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
17const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
18const ATTACHMENT_ID_FILE_EXTENSION_PATTERN = "[a-z0-9]{1,10}";
19const ATTACHMENT_ID_PATTERN = new RegExp(
20 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})(?:-(${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}))?$`,
21 "i",
22);
23
24export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
25const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
26const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;
27
28export function toSafeThreadAttachmentSegment(threadId: string): string | null {
29 const segment = threadId
30 .trim()
31 .toLowerCase()
32 .replace(/[^a-z0-9_-]+/gi, "-")
33 .replace(/-+/g, "-")
34 .replace(/^[-_]+|[-_]+$/g, "")
35 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
36 .replace(/[-_]+$/g, "");
37 if (segment.length === 0) {
38 return null;
39 }
40 return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
41}
42
43export function attachmentFileExtension(fileName: string): string {
44 const extension = NodePath.extname(fileName).toLowerCase();
45 // ".part" is reserved for in-flight uploads; a stored "archive.part" would
46 // look stale to sweepStalePendingAttachments and get deleted.
47 if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
48 return ".bin";
49 }
50 return extension;
51}
52
53function attachmentIdExtensionSuffix(extension: string | undefined): string {
54 if (!extension) {
55 return "";
56 }
57 const normalized = extension.replace(/^\./, "").toLowerCase();
58 return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
59 ? `-${normalized}`
60 : "-bin";
61}
62
63export function createPendingAttachmentId(extension?: string): string {
64 return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
65}
66
67export function parseAttachmentUuid(attachmentId: string): string | null {
68 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
69 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
70 return null;
71 }
72 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
73}
74
75export function parseAttachmentFileExtension(attachmentId: string): string | null {
76 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
77 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
78 return null;
79 }
80 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
81}
82
83export function createAttachmentId(threadId: string, extension?: string): string | null {
84 const threadSegment = toSafeThreadAttachmentSegment(threadId);
85 if (!threadSegment) {
86 return null;
87 }
88 return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
89}
90
91export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
92 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
93 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
94 return null;
95 }
96 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
97 if (!match) {
98 return null;
99 }
100 return match[1]?.toLowerCase() ?? null;
101}
102
103/** Null for attachment types this build does not know; callers skip those. */
104export function attachmentRelativePath(attachment: ChatAttachment): string | null {
105 switch (attachment.type) {
106 case "image": {
107 const extension = inferImageExtension({
108 mimeType: attachment.mimeType,
109 fileName: attachment.name,
110 });
111 return `${attachment.id}${extension}`;
112 }
113 case "file":
114 return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
115 default:
116 return null;
117 }
118}
119
120export function resolveAttachmentPath(input: {
121 readonly attachmentsDir: string;
122 readonly attachment: ChatAttachment;
123}): string | null {
124 const relativePath = attachmentRelativePath(input.attachment);
125 if (!relativePath) {
126 return null;
127 }
128 return resolveAttachmentRelativePath({
129 attachmentsDir: input.attachmentsDir,
130 relativePath,
131 });
132}
133
134export function resolveAttachmentPathById(input: {
135 readonly attachmentsDir: string;
136 readonly attachmentId: string;
137}): string | null {
138 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
139 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
140 return null;
141 }
142 const fileExtension = parseAttachmentFileExtension(normalizedId);
143 if (fileExtension) {
144 const filePath = resolveAttachmentRelativePath({
145 attachmentsDir: input.attachmentsDir,
146 relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
147 });
148 return filePath && NodeFS.existsSync(filePath) ? filePath : null;
149 }
150 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
151 const maybePath = resolveAttachmentRelativePath({
152 attachmentsDir: input.attachmentsDir,
153 relativePath: `${normalizedId}${extension}`,
154 });
155 if (maybePath && NodeFS.existsSync(maybePath)) {
156 return maybePath;
157 }
158 }
159 return null;
160}
161
162export type AttachmentClaimPlan =
163 | {
164 readonly ok: true;
165 readonly finalId: string;
166 readonly currentPath: string;
167 readonly finalPath: string;
168 }
169 | { readonly ok: false; readonly reason: string };
170
171export function planAttachmentClaim(input: {
172 readonly attachmentsDir: string;
173 readonly threadId: string;
174 readonly attachmentId: string;
175}): AttachmentClaimPlan {
176 const uuid = parseAttachmentUuid(input.attachmentId);
177 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
178 if (!uuid || !requestedSegment) {
179 return { ok: false, reason: "invalid attachment id" };
180 }
181
182 if (!toSafeThreadAttachmentSegment(input.threadId)) {
183 return { ok: false, reason: "invalid thread id" };
184 }
185 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
186 return { ok: false, reason: "attachment must be a pending upload" };
187 }
188
189 const currentPath = resolveAttachmentPathById({
190 attachmentsDir: input.attachmentsDir,
191 attachmentId: input.attachmentId,
192 });
193 if (!currentPath) {
194 return { ok: false, reason: "attachment not found (removed or expired)" };
195 }
196 const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
197 const finalId = createAttachmentId(input.threadId, fileExtension);
198 if (!finalId) {
199 return { ok: false, reason: "failed to create attachment id" };
200 }
201
202 const expectedFinalPath = resolveAttachmentRelativePath({
203 attachmentsDir: input.attachmentsDir,
204 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
205 });
206 if (!expectedFinalPath) {
207 return { ok: false, reason: "failed to resolve attachment path" };
208 }
209 return {
210 ok: true,
211 finalId,
212 currentPath,
213 finalPath: expectedFinalPath,
214 };
215}
216
217export function sweepStalePendingAttachments(input: {
218 readonly attachmentsDir: string;
219 readonly nowMs: number;
220}): { readonly deleted: number } {
221 let entries: string[];
222 try {
223 entries = NodeFS.readdirSync(input.attachmentsDir);
224 } catch {
225 return { deleted: 0 };
226 }
227
228 let deleted = 0;
229 for (const entry of entries) {
230 const isPartial = entry.endsWith(".part");
231 if (!isPartial) {
232 const attachmentId = parseAttachmentIdFromRelativePath(entry);
233 if (
234 !attachmentId ||
235 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
236 ) {
237 continue;
238 }
239 }
240
241 const resolved = resolveAttachmentRelativePath({
242 attachmentsDir: input.attachmentsDir,
243 relativePath: entry,
244 });
245 if (!resolved) {
246 continue;
247 }
248 try {
249 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
250 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
251 NodeFS.unlinkSync(resolved);
252 deleted += 1;
253 }
254 } catch {
255 continue;
256 }
257 }
258
259 return { deleted };
260}
261
262export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
263 const normalized = normalizeAttachmentRelativePath(relativePath);
264 if (!normalized || normalized.includes("/")) {
265 return null;
266 }
267 const extensionIndex = normalized.lastIndexOf(".");
268 if (extensionIndex <= 0) {
269 return null;
270 }
271 const id = normalized.slice(0, extensionIndex);
272 return id.length > 0 && !id.includes(".") ? id : null;
273}