Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- exclusive copy and streaming hashes are filesystem boundaries missing from Effect's API.
2import * as NodeCrypto from "node:crypto";
3import * as NodeFSP from "node:fs/promises";
4import {
5 ATTACHMENT_UPLOAD_URL_TTL_MS,
6 type AttachmentCreateUploadUrlInput,
7 AttachmentUploadSigningKeyError,
8} from "@t3tools/contracts";
9import { isSvgAttachment } from "@t3tools/shared/image";
10import * as Clock from "effect/Clock";
11import * as SecureRandom from "effect/crypto/SecureRandom";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as PlatformError from "effect/PlatformError";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import type * as HttpServerRequest from "effect/http/HttpServerRequest";
20
21import {
22 attachmentFileExtension,
23 createPendingAttachmentId,
24 parseThreadSegmentFromAttachmentId,
25 PENDING_ATTACHMENT_THREAD_SEGMENT,
26 resolveAttachmentPathById,
27 sweepStalePendingAttachments,
28} from "../attachmentStore.ts";
29import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
30import {
31 base64UrlDecodeUtf8,
32 base64UrlEncode,
33 signPayload,
34 timingSafeEqualBase64Url,
35} from "../auth/utils.ts";
36import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
37import * as ServerConfig from "../config.ts";
38import { inferImageExtension } from "../imageMime.ts";
39import * as DocumentText from "../provider/DocumentText.ts";
40
41export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
42
43const SIGNING_SECRET_NAME = "asset-access-signing-key";
44const PENDING_ATTACHMENT_SWEEP_INTERVAL_MS = 15 * 60_000;
45const lastPendingSweepByDirectory = new Map<string, number>();
46
47const AttachmentUploadClaims = Schema.Struct({
48 version: Schema.Literal(1),
49 kind: Schema.Literal("attachment-upload"),
50 type: Schema.Literals(["image", "file"]).pipe(
51 Schema.withDecodingDefault(Effect.succeed("image" as const)),
52 ),
53 attachmentId: Schema.String,
54 name: Schema.String,
55 mimeType: Schema.String,
56 sizeBytes: Schema.Number,
57 expiresAt: Schema.Number,
58});
59export type AttachmentUploadClaims = typeof AttachmentUploadClaims.Type;
60
61const attachmentUploadClaimsJson = Schema.fromJsonString(AttachmentUploadClaims);
62const decodeAttachmentUploadClaims = Schema.decodeUnknownOption(attachmentUploadClaimsJson);
63const encodeAttachmentUploadClaims = Schema.encodeSync(attachmentUploadClaimsJson);
64
65function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null {
66 try {
67 return Option.getOrNull(decodeAttachmentUploadClaims(base64UrlDecodeUtf8(encodedPayload)));
68 } catch {
69 return null;
70 }
71}
72
73const loadSigningSecret = Effect.gen(function* () {
74 const secretStore = yield* ServerSecretStore.ServerSecretStore;
75 return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
76});
77
78export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
79 input: AttachmentCreateUploadUrlInput,
80) {
81 const secret = yield* loadSigningSecret.pipe(
82 Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
83 );
84 const config = yield* ServerConfig.ServerConfig;
85 const nowMs = yield* Clock.currentTimeMillis;
86 const previousSweep = lastPendingSweepByDirectory.get(config.attachmentsDir);
87 if (
88 previousSweep === undefined ||
89 nowMs - previousSweep >= PENDING_ATTACHMENT_SWEEP_INTERVAL_MS
90 ) {
91 lastPendingSweepByDirectory.set(config.attachmentsDir, nowMs);
92 const swept = sweepStalePendingAttachments({
93 attachmentsDir: config.attachmentsDir,
94 nowMs,
95 });
96 if (swept.deleted > 0) {
97 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
98 }
99 }
100
101 const attachmentType = input.type ?? "image";
102 const name =
103 attachmentType === "file" && isSvgAttachment(input) && !/\.svg$/i.test(input.name)
104 ? `${input.name}.svg`
105 : input.name;
106 const attachmentId = createPendingAttachmentId(
107 attachmentType === "file" ? attachmentFileExtension(name) : undefined,
108 );
109 const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
110 const encodedPayload = base64UrlEncode(
111 encodeAttachmentUploadClaims({
112 version: 1,
113 kind: "attachment-upload",
114 type: attachmentType,
115 attachmentId,
116 name,
117 mimeType: input.mimeType,
118 sizeBytes: input.sizeBytes,
119 expiresAt,
120 }),
121 );
122
123 return {
124 attachmentId,
125 relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,
126 expiresAt,
127 };
128});
129
130export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
131 token: string,
132) {
133 const [encodedPayload, signature, unexpectedSegment] = token.split(".");
134 if (!encodedPayload || !signature || unexpectedSegment) {
135 return null;
136 }
137
138 const secret = yield* loadSigningSecret.pipe(
139 Effect.tapError((cause) =>
140 Effect.logError("Failed to load the attachment upload signing key.", { cause }),
141 ),
142 Effect.orElseSucceed(() => null),
143 );
144 if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {
145 return null;
146 }
147
148 const claims = decodeClaims(encodedPayload);
149 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) {
150 return null;
151 }
152 return claims;
153});
154
155export type StoreAttachmentUploadResult =
156 | { readonly ok: true }
157 | { readonly ok: false; readonly status: number; readonly detail: string };
158
159export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
160 claims: AttachmentUploadClaims,
161 body: Uint8Array | HttpServerRequest.HttpServerRequest["stream"],
162) {
163 if (body instanceof Uint8Array && body.byteLength !== claims.sizeBytes) {
164 return {
165 ok: false,
166 status: 400,
167 detail: `Body was ${body.byteLength} bytes, expected ${claims.sizeBytes}.`,
168 } satisfies StoreAttachmentUploadResult;
169 }
170
171 const config = yield* ServerConfig.ServerConfig;
172 const extension =
173 claims.type === "file"
174 ? attachmentFileExtension(claims.name)
175 : inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name });
176 const relativePath = `${claims.attachmentId}${extension}`;
177 const finalPath = resolveAttachmentRelativePath({
178 attachmentsDir: config.attachmentsDir,
179 relativePath,
180 });
181 const random = yield* SecureRandom.SecureRandom;
182 const partId = yield* random.uuidV4();
183 const partPath = resolveAttachmentRelativePath({
184 attachmentsDir: config.attachmentsDir,
185 relativePath: `${relativePath}.${partId}.part`,
186 });
187 if (!finalPath || !partPath) {
188 return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
189 }
190
191 const fileSystem = yield* FileSystem.FileSystem;
192 const path = yield* Path.Path;
193 let receivedBytes = 0;
194 const bodyStream = body instanceof Uint8Array ? Stream.make(body) : body;
195 return yield* Effect.gen(function* () {
196 yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
197 yield* Stream.run(
198 bodyStream.pipe(
199 Stream.takeWhile((chunk) => {
200 receivedBytes += chunk.byteLength;
201 return receivedBytes <= claims.sizeBytes;
202 }),
203 ),
204 fileSystem.sink(partPath),
205 );
206 if (receivedBytes !== claims.sizeBytes) {
207 return {
208 ok: false,
209 status: 400,
210 detail: `Body was ${receivedBytes} bytes, expected ${claims.sizeBytes}.`,
211 } satisfies StoreAttachmentUploadResult;
212 }
213 // Publishing without replacement keeps an upload and its cached text immutable.
214 const published = yield* fileSystem.link(partPath, finalPath).pipe(
215 Effect.map(() => true),
216 Effect.catch((error) => {
217 if (error.reason._tag === "AlreadyExists") return Effect.succeed(false);
218 return Effect.tryPromise({
219 try: () => NodeFSP.copyFile(partPath, finalPath, NodeFSP.constants.COPYFILE_EXCL),
220 catch: (cause) =>
221 PlatformError.systemError({
222 _tag:
223 cause instanceof Error && "code" in cause && cause.code === "EEXIST"
224 ? "AlreadyExists"
225 : "Unknown",
226 module: "FileSystem",
227 method: "copyFile",
228 pathOrDescriptor: finalPath,
229 cause,
230 }),
231 }).pipe(
232 Effect.as(true),
233 Effect.catchIf(
234 (error) => error.reason._tag === "AlreadyExists",
235 () => Effect.succeed(false),
236 ),
237 );
238 }),
239 );
240 if (!published) {
241 if (Number((yield* fileSystem.stat(finalPath)).size) !== receivedBytes) {
242 return { ok: false, status: 409, detail: "Attachment already uploaded." };
243 }
244 const hashes = yield* Effect.forEach([partPath, finalPath], (file) =>
245 fileSystem.stream(file).pipe(
246 Stream.runFold(
247 () => NodeCrypto.createHash("sha256"),
248 (hash, chunk) => hash.update(chunk),
249 ),
250 Effect.map((hash) => hash.digest("hex")),
251 ),
252 );
253 if (hashes[0] !== hashes[1]) {
254 return { ok: false, status: 409, detail: "Attachment already uploaded." };
255 }
256 }
257 const documents = yield* DocumentText.DocumentText;
258 yield* documents.ensure(finalPath);
259 return { ok: true } satisfies StoreAttachmentUploadResult;
260 }).pipe(
261 Effect.catch((cause) =>
262 Effect.logError("Failed to persist attachment upload.", {
263 attachmentId: claims.attachmentId,
264 cause,
265 }).pipe(
266 Effect.as({
267 ok: false,
268 status: 500,
269 detail: "Failed to persist upload.",
270 } satisfies StoreAttachmentUploadResult),
271 ),
272 ),
273 Effect.ensuring(
274 fileSystem.remove(partPath, { force: true }).pipe(Effect.orElseSucceed(() => undefined)),
275 ),
276 );
277});
278
279export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
280 attachmentId: string,
281) {
282 if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
283 return;
284 }
285
286 const config = yield* ServerConfig.ServerConfig;
287 const attachmentPath = resolveAttachmentPathById({
288 attachmentsDir: config.attachmentsDir,
289 attachmentId,
290 });
291 if (!attachmentPath) {
292 return;
293 }
294
295 const fileSystem = yield* FileSystem.FileSystem;
296 yield* fileSystem.remove(attachmentPath, { force: true }).pipe(Effect.orElseSucceed(() => {}));
297 yield* fileSystem.remove(`${attachmentPath}.txt`, { force: true }).pipe(Effect.ignore);
298});