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