Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AttachmentUpload.ts

214 lines7.0 KB

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