Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import {
4 ATTACHMENT_UPLOAD_URL_TTL_MS,
5 type AttachmentCreateUploadUrlInput,
6 AttachmentUploadSigningKeyError,
7} from "@t3tools/contracts";
8import * as Clock from "effect/Clock";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
16
17import {
18 attachmentFileExtension,
19 createPendingAttachmentId,
20 parseThreadSegmentFromAttachmentId,
21 PENDING_ATTACHMENT_THREAD_SEGMENT,
22 resolveAttachmentPathById,
23 sweepStalePendingAttachments,
24} from "../attachmentStore.ts";
25import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
26import {
27 base64UrlDecodeUtf8,
28 base64UrlEncode,
29 signPayload,
30 timingSafeEqualBase64Url,
31} from "../auth/utils.ts";
32import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
33import * as ServerConfig from "../config.ts";
34import { inferImageExtension } from "../imageMime.ts";
35
36export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
37
38// Asset download tokens share this key, but their signed claim kind is different.
39const SIGNING_SECRET_NAME = "asset-access-signing-key";
40const PENDING_ATTACHMENT_SWEEP_INTERVAL_MS = 15 * 60_000;
41const lastPendingSweepByDirectory = new Map<string, number>();
42
43const AttachmentUploadClaims = Schema.Struct({
44 version: Schema.Literal(1),
45 kind: Schema.Literal("attachment-upload"),
46 type: Schema.Literals(["image", "file"]).pipe(
47 Schema.withDecodingDefault(Effect.succeed("image" as const)),
48 ),
49 attachmentId: Schema.String,
50 name: Schema.String,
51 mimeType: Schema.String,
52 sizeBytes: Schema.Number,
53 expiresAt: Schema.Number,
54});
55export type AttachmentUploadClaims = typeof AttachmentUploadClaims.Type;
56
57const attachmentUploadClaimsJson = Schema.fromJsonString(AttachmentUploadClaims);
58const decodeAttachmentUploadClaims = Schema.decodeUnknownOption(attachmentUploadClaimsJson);
59const encodeAttachmentUploadClaims = Schema.encodeSync(attachmentUploadClaimsJson);
60
61function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null {
62 try {
63 return Option.getOrNull(decodeAttachmentUploadClaims(base64UrlDecodeUtf8(encodedPayload)));
64 } catch {
65 return null;
66 }
67}
68
69const loadSigningSecret = Effect.gen(function* () {
70 const secretStore = yield* ServerSecretStore.ServerSecretStore;
71 return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
72});
73
74export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
75 input: AttachmentCreateUploadUrlInput,
76) {
77 const secret = yield* loadSigningSecret.pipe(
78 Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
79 );
80 const config = yield* ServerConfig.ServerConfig;
81 const nowMs = yield* Clock.currentTimeMillis;
82 const previousSweep = lastPendingSweepByDirectory.get(config.attachmentsDir);
83 if (
84 previousSweep === undefined ||
85 nowMs - previousSweep >= PENDING_ATTACHMENT_SWEEP_INTERVAL_MS
86 ) {
87 lastPendingSweepByDirectory.set(config.attachmentsDir, nowMs);
88 const swept = sweepStalePendingAttachments({
89 attachmentsDir: config.attachmentsDir,
90 nowMs,
91 });
92 if (swept.deleted > 0) {
93 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
94 }
95 }
96
97 const attachmentType = input.type ?? "image";
98 const attachmentId = createPendingAttachmentId(
99 attachmentType === "file" ? attachmentFileExtension(input.name) : undefined,
100 );
101 const expiresAt = nowMs + ATTACHMENT_UPLOAD_URL_TTL_MS;
102 const encodedPayload = base64UrlEncode(
103 encodeAttachmentUploadClaims({
104 version: 1,
105 kind: "attachment-upload",
106 type: attachmentType,
107 attachmentId,
108 name: input.name,
109 mimeType: input.mimeType,
110 sizeBytes: input.sizeBytes,
111 expiresAt,
112 }),
113 );
114
115 return {
116 attachmentId,
117 relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`,
118 expiresAt,
119 };
120});
121
122export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
123 token: string,
124) {
125 const [encodedPayload, signature, unexpectedSegment] = token.split(".");
126 if (!encodedPayload || !signature || unexpectedSegment) {
127 return null;
128 }
129
130 const secret = yield* loadSigningSecret.pipe(
131 Effect.tapError((cause) =>
132 Effect.logError("Failed to load the attachment upload signing key.", { cause }),
133 ),
134 Effect.orElseSucceed(() => null),
135 );
136 if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) {
137 return null;
138 }
139
140 const claims = decodeClaims(encodedPayload);
141 if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) {
142 return null;
143 }
144 return claims;
145});
146
147export type StoreAttachmentUploadResult =
148 | { readonly ok: true }
149 | { readonly ok: false; readonly status: number; readonly detail: string };
150
151export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
152 claims: AttachmentUploadClaims,
153 body: Uint8Array | HttpServerRequest.HttpServerRequest["stream"],
154) {
155 if (body instanceof Uint8Array && body.byteLength !== claims.sizeBytes) {
156 return {
157 ok: false,
158 status: 400,
159 detail: `Body was ${body.byteLength} bytes, expected ${claims.sizeBytes}.`,
160 } satisfies StoreAttachmentUploadResult;
161 }
162
163 const config = yield* ServerConfig.ServerConfig;
164 const extension =
165 claims.type === "file"
166 ? attachmentFileExtension(claims.name)
167 : inferImageExtension({ mimeType: claims.mimeType, fileName: claims.name });
168 const relativePath = `${claims.attachmentId}${extension}`;
169 const finalPath = resolveAttachmentRelativePath({
170 attachmentsDir: config.attachmentsDir,
171 relativePath,
172 });
173 const partPath = resolveAttachmentRelativePath({
174 attachmentsDir: config.attachmentsDir,
175 relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
176 });
177 if (!finalPath || !partPath) {
178 return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
179 }
180
181 const fileSystem = yield* FileSystem.FileSystem;
182 const path = yield* Path.Path;
183 let receivedBytes = 0;
184 const bodyStream = body instanceof Uint8Array ? Stream.make(body) : body;
185 return yield* Effect.gen(function* () {
186 yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
187 yield* Stream.run(
188 bodyStream.pipe(
189 Stream.takeWhile((chunk) => {
190 receivedBytes += chunk.byteLength;
191 return receivedBytes <= claims.sizeBytes;
192 }),
193 ),
194 fileSystem.sink(partPath),
195 );
196 if (receivedBytes !== claims.sizeBytes) {
197 return {
198 ok: false,
199 status: 400,
200 detail: `Body was ${receivedBytes} bytes, expected ${claims.sizeBytes}.`,
201 } satisfies StoreAttachmentUploadResult;
202 }
203 yield* fileSystem.rename(partPath, finalPath);
204 return { ok: true } satisfies StoreAttachmentUploadResult;
205 }).pipe(
206 Effect.catch((cause) =>
207 Effect.logError("Failed to persist attachment upload.", {
208 attachmentId: claims.attachmentId,
209 cause,
210 }).pipe(
211 Effect.as({
212 ok: false,
213 status: 500,
214 detail: "Failed to persist upload.",
215 } satisfies StoreAttachmentUploadResult),
216 ),
217 ),
218 Effect.ensuring(
219 fileSystem.remove(partPath, { force: true }).pipe(Effect.orElseSucceed(() => undefined)),
220 ),
221 );
222});
223
224export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
225 attachmentId: string,
226) {
227 if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
228 return;
229 }
230
231 const config = yield* ServerConfig.ServerConfig;
232 const attachmentPath = resolveAttachmentPathById({
233 attachmentsDir: config.attachmentsDir,
234 attachmentId,
235 });
236 if (!attachmentPath) {
237 return;
238 }
239
240 const fileSystem = yield* FileSystem.FileSystem;
241 yield* fileSystem.remove(attachmentPath, { force: true }).pipe(Effect.orElseSucceed(() => {}));
242});