@getstrata/core 3.0.8 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -877
- package/README.md +20 -57
- package/dist/core/database/definitions.d.ts +8 -2
- package/dist/core/database/driverPorts.d.ts +1 -1
- package/dist/core/database/index.d.ts +3 -2
- package/dist/core/database/model.d.ts +19 -4
- package/dist/core/database/modelAuthoring.d.ts +64 -0
- package/dist/core/database/modelRegistry.d.ts +5 -1
- package/dist/core/database/modelRelationTypes.d.ts +14 -0
- package/dist/core/database/ormInternal.d.ts +2 -1
- package/dist/core/database/ormRuntime.d.ts +2 -1
- package/dist/core/http/index.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +1 -0
- package/dist/core/http/streamingUpload.d.ts +20 -0
- package/dist/core/http/uploadContent.d.ts +6 -0
- package/dist/core/media/imageTransform.d.ts +25 -1
- package/dist/entries/database/bindings.js +34 -11
- package/dist/entries/database/definitions.js +6 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +3 -1
- package/dist/entries/http/parseMultipartUpload.js +408 -20
- package/dist/entries/media/imageTransform.js +110 -20
- package/dist/framework/public-api.d.ts +4 -3
- package/dist/index.js +70 -102
- package/dist/internal/ormRuntime.js +173 -9
- package/package.json +2 -2
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// ../../src/core/http/parseMultipartUpload.ts
|
|
3
|
-
import { BadRequestError, PayloadTooLargeError } from "@getstrata/core/errors/http";
|
|
3
|
+
import { BadRequestError as BadRequestError3, PayloadTooLargeError as PayloadTooLargeError2 } from "@getstrata/core/errors/http";
|
|
4
|
+
|
|
5
|
+
// ../../src/core/http/streamingUpload.ts
|
|
6
|
+
import { Buffer } from "buffer";
|
|
7
|
+
import { BadRequestError as BadRequestError2, PayloadTooLargeError } from "@getstrata/core/errors/http";
|
|
8
|
+
|
|
9
|
+
// ../../src/core/http/uploadContent.ts
|
|
10
|
+
import { BadRequestError } from "@getstrata/core/errors/http";
|
|
11
|
+
function normalizeMimeType(mimeType) {
|
|
12
|
+
return mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
13
|
+
}
|
|
14
|
+
function assertUploadContentType(prefix, mimeType) {
|
|
15
|
+
const mime = normalizeMimeType(mimeType);
|
|
16
|
+
const starts = (...bytes) => bytes.every((byte, index) => prefix[index] === byte);
|
|
17
|
+
const ascii = (offset, text) => [...text].every((char, index) => prefix[offset + index] === char.charCodeAt(0));
|
|
18
|
+
let valid = true;
|
|
19
|
+
switch (mime) {
|
|
20
|
+
case "image/jpeg":
|
|
21
|
+
valid = starts(255, 216, 255);
|
|
22
|
+
break;
|
|
23
|
+
case "image/png":
|
|
24
|
+
valid = starts(137, 80, 78, 71, 13, 10, 26, 10);
|
|
25
|
+
break;
|
|
26
|
+
case "image/gif":
|
|
27
|
+
valid = ascii(0, "GIF87a") || ascii(0, "GIF89a");
|
|
28
|
+
break;
|
|
29
|
+
case "image/webp":
|
|
30
|
+
valid = ascii(0, "RIFF") && ascii(8, "WEBP");
|
|
31
|
+
break;
|
|
32
|
+
case "application/pdf":
|
|
33
|
+
valid = ascii(0, "%PDF-");
|
|
34
|
+
break;
|
|
35
|
+
case "application/zip":
|
|
36
|
+
case "application/x-zip-compressed":
|
|
37
|
+
valid = starts(80, 75, 3, 4) || starts(80, 75, 5, 6) || starts(80, 75, 7, 8);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
if (!valid)
|
|
41
|
+
throw new BadRequestError("Uploaded content does not match its declared type.");
|
|
42
|
+
}
|
|
43
|
+
function uploadTextDecoder(mimeType) {
|
|
44
|
+
return ["text/plain", "text/csv", "application/json"].includes(normalizeMimeType(mimeType)) ? new TextDecoder("utf-8", { fatal: true }) : undefined;
|
|
45
|
+
}
|
|
46
|
+
function validateUploadText(decoder, bytes) {
|
|
47
|
+
if (!decoder)
|
|
48
|
+
return;
|
|
49
|
+
try {
|
|
50
|
+
const text = decoder.decode(bytes, { stream: bytes !== undefined });
|
|
51
|
+
for (let index = 0;index < text.length; index++) {
|
|
52
|
+
const code = text.charCodeAt(index);
|
|
53
|
+
if (code < 32 && code !== 9 && code !== 10 && code !== 13)
|
|
54
|
+
throw new Error("Binary text");
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
throw new BadRequestError("Uploaded text must contain valid UTF-8 text.");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
4
60
|
|
|
5
61
|
// ../../src/core/config/envSchema.ts
|
|
6
62
|
function defineEnvSchema(schema) {
|
|
@@ -84,19 +140,349 @@ var DEFAULT_UPLOAD_POLICY = Object.freeze({
|
|
|
84
140
|
function resolveMaxUploadBytes(value) {
|
|
85
141
|
return resolveEnv({ MAX_UPLOAD_BYTES: { integer: true, minimum: 1, default: String(DEFAULT_MAX_UPLOAD_BYTES) } }, { MAX_UPLOAD_BYTES: value }).MAX_UPLOAD_BYTES;
|
|
86
142
|
}
|
|
87
|
-
function
|
|
143
|
+
function normalizeMimeType2(mimeType) {
|
|
88
144
|
return mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
89
145
|
}
|
|
90
146
|
function isAllowedMimeType(mimeType, allowUnknownMime = false) {
|
|
91
|
-
const normalized =
|
|
147
|
+
const normalized = normalizeMimeType2(mimeType);
|
|
92
148
|
if (!normalized || normalized === "application/octet-stream") {
|
|
93
149
|
return allowUnknownMime;
|
|
94
150
|
}
|
|
95
151
|
return ALLOWED_UPLOAD_MIME_TYPES.has(normalized);
|
|
96
152
|
}
|
|
97
153
|
|
|
154
|
+
// ../../src/core/http/streamingUpload.ts
|
|
155
|
+
var HEADER_LIMIT = 16 * 1024;
|
|
156
|
+
var ENVELOPE_LIMIT = 64 * 1024;
|
|
157
|
+
var CRLF = Buffer.from(`\r
|
|
158
|
+
`);
|
|
159
|
+
var HEADER_END = Buffer.from(`\r
|
|
160
|
+
\r
|
|
161
|
+
`);
|
|
162
|
+
|
|
163
|
+
class UploadedFile {
|
|
164
|
+
fileName;
|
|
165
|
+
mimeType;
|
|
166
|
+
contents;
|
|
167
|
+
consumed = false;
|
|
168
|
+
constructor(fileName, mimeType, contents) {
|
|
169
|
+
this.fileName = fileName;
|
|
170
|
+
this.mimeType = mimeType;
|
|
171
|
+
this.contents = contents;
|
|
172
|
+
}
|
|
173
|
+
stream() {
|
|
174
|
+
if (this.consumed)
|
|
175
|
+
throw new TypeError("Uploaded file has already been consumed.");
|
|
176
|
+
this.consumed = true;
|
|
177
|
+
return this.contents;
|
|
178
|
+
}
|
|
179
|
+
bytes() {
|
|
180
|
+
return new Response(this.stream()).bytes();
|
|
181
|
+
}
|
|
182
|
+
async discard() {
|
|
183
|
+
await this.stream().cancel();
|
|
184
|
+
}
|
|
185
|
+
async store(storage, directory = "uploads") {
|
|
186
|
+
if (typeof directory !== "string" || /[\\\0]/.test(directory) || directory !== "" && directory.split("/").some((part) => !part || part === "." || part === ".."))
|
|
187
|
+
throw new TypeError("Upload directory must be a relative path without traversal.");
|
|
188
|
+
const key = `${directory ? `${directory}/` : ""}${crypto.randomUUID()}`;
|
|
189
|
+
const reader = this.stream().getReader();
|
|
190
|
+
let completed = false;
|
|
191
|
+
const stream = new ReadableStream({
|
|
192
|
+
async pull(controller) {
|
|
193
|
+
try {
|
|
194
|
+
const next = await reader.read();
|
|
195
|
+
if (next.done) {
|
|
196
|
+
completed = true;
|
|
197
|
+
controller.close();
|
|
198
|
+
} else
|
|
199
|
+
controller.enqueue(next.value);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
controller.error(error);
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
cancel: (reason) => reader.cancel(reason)
|
|
205
|
+
}, { highWaterMark: 0 });
|
|
206
|
+
try {
|
|
207
|
+
await storage.writeStream(key, stream);
|
|
208
|
+
if (!completed)
|
|
209
|
+
throw new TypeError("Storage driver did not consume the upload.");
|
|
210
|
+
return key;
|
|
211
|
+
} catch (error) {
|
|
212
|
+
await reader.cancel(error).catch(() => {});
|
|
213
|
+
try {
|
|
214
|
+
await storage.delete(key);
|
|
215
|
+
} catch (cleanup) {
|
|
216
|
+
throw new AggregateError([error, cleanup], "Upload failed and partial-object cleanup failed.");
|
|
217
|
+
}
|
|
218
|
+
throw error;
|
|
219
|
+
} finally {
|
|
220
|
+
reader.releaseLock();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
class MultipartReader {
|
|
226
|
+
reader;
|
|
227
|
+
boundary;
|
|
228
|
+
maxBytes;
|
|
229
|
+
buffer = Buffer.alloc(0);
|
|
230
|
+
ended = false;
|
|
231
|
+
closed = false;
|
|
232
|
+
total = 0;
|
|
233
|
+
parts = 0;
|
|
234
|
+
finished = false;
|
|
235
|
+
delimiter;
|
|
236
|
+
constructor(reader, boundary, maxBytes) {
|
|
237
|
+
this.reader = reader;
|
|
238
|
+
this.boundary = boundary;
|
|
239
|
+
this.maxBytes = maxBytes;
|
|
240
|
+
this.delimiter = Buffer.from(`\r
|
|
241
|
+
--${boundary}`);
|
|
242
|
+
}
|
|
243
|
+
async fill() {
|
|
244
|
+
const next = await this.reader.read();
|
|
245
|
+
if (next.done) {
|
|
246
|
+
this.ended = true;
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
this.total += next.value.byteLength;
|
|
250
|
+
if (this.total > this.maxBytes)
|
|
251
|
+
throw new PayloadTooLargeError("Multipart request exceeds its byte limit.");
|
|
252
|
+
const chunk = Buffer.from(next.value.buffer, next.value.byteOffset, next.value.byteLength);
|
|
253
|
+
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
|
|
254
|
+
}
|
|
255
|
+
async until(delimiter, limit) {
|
|
256
|
+
while (true) {
|
|
257
|
+
const index = this.buffer.indexOf(delimiter);
|
|
258
|
+
if (index >= 0 && index <= limit) {
|
|
259
|
+
const result = this.buffer.subarray(0, index);
|
|
260
|
+
this.buffer = this.buffer.subarray(index + delimiter.length);
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
if (index > limit || this.buffer.length > limit + delimiter.length)
|
|
264
|
+
throw new BadRequestError2("Multipart header exceeds its limit.");
|
|
265
|
+
if (this.ended)
|
|
266
|
+
throw new BadRequestError2("Truncated multipart request.");
|
|
267
|
+
await this.fill();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async start() {
|
|
271
|
+
const opening = await this.until(CRLF, 74);
|
|
272
|
+
if (opening.toString() !== `--${this.boundary}`)
|
|
273
|
+
throw new BadRequestError2("Invalid multipart opening boundary.");
|
|
274
|
+
}
|
|
275
|
+
async headers() {
|
|
276
|
+
if (++this.parts > 32)
|
|
277
|
+
throw new BadRequestError2("Too many multipart fields.");
|
|
278
|
+
const raw = await this.until(HEADER_END, HEADER_LIMIT);
|
|
279
|
+
let text;
|
|
280
|
+
try {
|
|
281
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
|
|
282
|
+
} catch {
|
|
283
|
+
throw new BadRequestError2("Invalid multipart headers.");
|
|
284
|
+
}
|
|
285
|
+
const headers = new Map;
|
|
286
|
+
for (const line of text.split(`\r
|
|
287
|
+
`)) {
|
|
288
|
+
const match = /^([!#$%&'*+.^_`|~\w-]+):[ \t]*([^\r\n\0]*)$/.exec(line);
|
|
289
|
+
if (!match)
|
|
290
|
+
throw new BadRequestError2("Invalid multipart header.");
|
|
291
|
+
const key = match[1].toLowerCase();
|
|
292
|
+
if (headers.has(key))
|
|
293
|
+
throw new BadRequestError2("Duplicate multipart header.");
|
|
294
|
+
headers.set(key, match[2].trim());
|
|
295
|
+
}
|
|
296
|
+
if (headers.has("content-transfer-encoding"))
|
|
297
|
+
throw new BadRequestError2("Encoded multipart parts are unsupported.");
|
|
298
|
+
const disposition = headers.get("content-disposition") ?? "";
|
|
299
|
+
if (!/^form-data\s*(;|$)/i.test(disposition))
|
|
300
|
+
throw new BadRequestError2("Expected a form-data disposition.");
|
|
301
|
+
const params = new Map;
|
|
302
|
+
let rest = disposition.replace(/^form-data\s*/i, "");
|
|
303
|
+
while (rest) {
|
|
304
|
+
const match = /^;\s*([\w-]+)\s*=\s*(?:"((?:[^"\\\r\n]|\\["\\])*)"|([!#$%&'*+.^_`|~\w-]+))\s*/.exec(rest);
|
|
305
|
+
if (!match)
|
|
306
|
+
throw new BadRequestError2("Invalid multipart disposition parameters.");
|
|
307
|
+
const key = match[1].toLowerCase();
|
|
308
|
+
if (params.has(key))
|
|
309
|
+
throw new BadRequestError2("Duplicate multipart disposition parameter.");
|
|
310
|
+
params.set(key, (match[2] ?? match[3]).replace(/\\(["\\])/g, "$1"));
|
|
311
|
+
rest = rest.slice(match[0].length);
|
|
312
|
+
}
|
|
313
|
+
const name = params.get("name");
|
|
314
|
+
if (!name)
|
|
315
|
+
throw new BadRequestError2("Multipart field name is required.");
|
|
316
|
+
return {
|
|
317
|
+
name,
|
|
318
|
+
fileName: params.get("filename"),
|
|
319
|
+
mimeType: (headers.get("content-type") ?? "application/octet-stream").split(";")[0]?.trim().toLowerCase() ?? ""
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
async* body() {
|
|
323
|
+
while (true) {
|
|
324
|
+
const index = this.buffer.indexOf(this.delimiter);
|
|
325
|
+
if (index >= 0) {
|
|
326
|
+
const suffix = index + this.delimiter.length;
|
|
327
|
+
while (!this.ended && this.buffer.length < suffix + 4)
|
|
328
|
+
await this.fill();
|
|
329
|
+
const next = this.buffer.subarray(suffix, suffix + 2).toString();
|
|
330
|
+
const final = next === "--" && (this.buffer.length === suffix + 2 && this.ended || this.buffer.subarray(suffix + 2, suffix + 4).equals(CRLF));
|
|
331
|
+
if (next === `\r
|
|
332
|
+
` || final) {
|
|
333
|
+
const body = this.buffer.subarray(0, index);
|
|
334
|
+
this.buffer = this.buffer.subarray(suffix + 2);
|
|
335
|
+
this.finished = final;
|
|
336
|
+
if (body.length)
|
|
337
|
+
yield body;
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const body = this.buffer.subarray(0, index + 2);
|
|
341
|
+
this.buffer = this.buffer.subarray(index + 2);
|
|
342
|
+
yield body;
|
|
343
|
+
} else {
|
|
344
|
+
const available = this.buffer.length - this.delimiter.length + 1;
|
|
345
|
+
if (available > 0) {
|
|
346
|
+
const body = this.buffer.subarray(0, available);
|
|
347
|
+
this.buffer = this.buffer.subarray(available);
|
|
348
|
+
yield body;
|
|
349
|
+
} else {
|
|
350
|
+
if (this.ended)
|
|
351
|
+
throw new BadRequestError2("Truncated multipart body.");
|
|
352
|
+
await this.fill();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async finish() {
|
|
358
|
+
if (this.buffer.length && !this.buffer.equals(CRLF))
|
|
359
|
+
throw new BadRequestError2("Unexpected data after multipart closing boundary.");
|
|
360
|
+
this.buffer = Buffer.alloc(0);
|
|
361
|
+
while (!this.ended) {
|
|
362
|
+
await this.fill();
|
|
363
|
+
if (this.buffer.length)
|
|
364
|
+
throw new BadRequestError2("Unexpected data after multipart closing boundary.");
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async close(reason) {
|
|
368
|
+
if (this.closed)
|
|
369
|
+
return;
|
|
370
|
+
this.closed = true;
|
|
371
|
+
try {
|
|
372
|
+
if (!this.ended)
|
|
373
|
+
await this.reader.cancel(reason);
|
|
374
|
+
} finally {
|
|
375
|
+
this.reader.releaseLock();
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async function parseMultipartUploadStream(request, fieldName = "file", policy = DEFAULT_UPLOAD_POLICY) {
|
|
380
|
+
if (!Number.isSafeInteger(policy.maxBytes) || policy.maxBytes <= 0 || policy.maxBytes > Number.MAX_SAFE_INTEGER - ENVELOPE_LIMIT)
|
|
381
|
+
throw new RangeError("Upload limit must be a positive safe integer.");
|
|
382
|
+
const maxBytes = policy.maxBytes;
|
|
383
|
+
const allowUnknownMime = policy.allowUnknownMime;
|
|
384
|
+
if (typeof allowUnknownMime !== "boolean")
|
|
385
|
+
throw new TypeError("Upload allowUnknownMime must be a boolean.");
|
|
386
|
+
const contentType = request.headers.get("content-type") ?? "";
|
|
387
|
+
const match = /^multipart\/form-data\s*;\s*boundary=(?:"([\w'()+,\-./:=? ]{1,70})"|([\w'()+,\-./:=?]{1,70}))\s*$/i.exec(contentType);
|
|
388
|
+
const boundary = match?.[1] ?? match?.[2];
|
|
389
|
+
if (!boundary || boundary.endsWith(" ") || !request.body)
|
|
390
|
+
throw new BadRequestError2("Expected multipart form data with a valid boundary and body.");
|
|
391
|
+
const parser = new MultipartReader(request.body.getReader(), boundary, maxBytes + ENVELOPE_LIMIT);
|
|
392
|
+
let metadataBytes = 0;
|
|
393
|
+
async function skipField() {
|
|
394
|
+
for await (const chunk of parser.body()) {
|
|
395
|
+
metadataBytes += chunk.byteLength;
|
|
396
|
+
if (metadataBytes > ENVELOPE_LIMIT)
|
|
397
|
+
throw new PayloadTooLargeError("Multipart fields exceed their byte limit.");
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
try {
|
|
401
|
+
await parser.start();
|
|
402
|
+
while (!parser.finished) {
|
|
403
|
+
const header = await parser.headers();
|
|
404
|
+
if (header.fileName === undefined) {
|
|
405
|
+
await skipField();
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (header.name !== fieldName)
|
|
409
|
+
throw new BadRequestError2(`Unexpected upload field "${header.name}".`);
|
|
410
|
+
if (!isAllowedMimeType(header.mimeType, allowUnknownMime))
|
|
411
|
+
throw new BadRequestError2(`File type "${header.mimeType}" is not allowed.`);
|
|
412
|
+
const mimeType = header.mimeType;
|
|
413
|
+
async function* file() {
|
|
414
|
+
let size = 0;
|
|
415
|
+
let prefix = Buffer.alloc(0);
|
|
416
|
+
let checked = false;
|
|
417
|
+
const decoder = uploadTextDecoder(mimeType);
|
|
418
|
+
try {
|
|
419
|
+
for await (const chunk of parser.body()) {
|
|
420
|
+
size += chunk.byteLength;
|
|
421
|
+
if (size > maxBytes)
|
|
422
|
+
throw new PayloadTooLargeError("Upload exceeds its byte limit.");
|
|
423
|
+
validateUploadText(decoder, chunk);
|
|
424
|
+
if (!checked) {
|
|
425
|
+
const take = Math.min(12 - prefix.length, chunk.byteLength);
|
|
426
|
+
prefix = Buffer.concat([prefix, chunk.subarray(0, take)]);
|
|
427
|
+
if (prefix.length < 12)
|
|
428
|
+
continue;
|
|
429
|
+
assertUploadContentType(prefix, mimeType);
|
|
430
|
+
checked = true;
|
|
431
|
+
yield prefix;
|
|
432
|
+
if (take < chunk.byteLength)
|
|
433
|
+
yield chunk.subarray(take);
|
|
434
|
+
} else
|
|
435
|
+
yield chunk;
|
|
436
|
+
}
|
|
437
|
+
if (!size)
|
|
438
|
+
throw new BadRequestError2("Uploaded file is empty.");
|
|
439
|
+
if (!checked) {
|
|
440
|
+
assertUploadContentType(prefix, mimeType);
|
|
441
|
+
yield prefix;
|
|
442
|
+
}
|
|
443
|
+
validateUploadText(decoder);
|
|
444
|
+
while (!parser.finished) {
|
|
445
|
+
const next = await parser.headers();
|
|
446
|
+
if (next.fileName !== undefined)
|
|
447
|
+
throw new BadRequestError2("Only one uploaded file is accepted.");
|
|
448
|
+
await skipField();
|
|
449
|
+
}
|
|
450
|
+
await parser.finish();
|
|
451
|
+
} finally {
|
|
452
|
+
await parser.close();
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const iterator = file();
|
|
456
|
+
const stream = new ReadableStream({
|
|
457
|
+
async pull(controller) {
|
|
458
|
+
try {
|
|
459
|
+
const next = await iterator.next();
|
|
460
|
+
if (next.done)
|
|
461
|
+
controller.close();
|
|
462
|
+
else
|
|
463
|
+
controller.enqueue(next.value);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
controller.error(error);
|
|
466
|
+
}
|
|
467
|
+
},
|
|
468
|
+
async cancel(reason) {
|
|
469
|
+
await parser.close(reason);
|
|
470
|
+
await iterator.return(undefined);
|
|
471
|
+
}
|
|
472
|
+
}, { highWaterMark: 0 });
|
|
473
|
+
const name = header.fileName.split(/[/\\]/).pop()?.trim() ?? "upload";
|
|
474
|
+
const safeName = name.replace(/[^\w.\-()+ ]+/g, "_").slice(0, 200) || "upload";
|
|
475
|
+
return new UploadedFile(safeName, mimeType, stream);
|
|
476
|
+
}
|
|
477
|
+
throw new BadRequestError2(`Missing upload field "${fieldName}".`);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
await parser.close(error);
|
|
480
|
+
throw error;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
98
484
|
// ../../src/core/http/parseMultipartUpload.ts
|
|
99
|
-
function
|
|
485
|
+
function normalizeMimeType3(mimeType) {
|
|
100
486
|
return mimeType.split(";")[0]?.trim().toLowerCase() || "application/octet-stream";
|
|
101
487
|
}
|
|
102
488
|
function sanitizeUploadFileName(name) {
|
|
@@ -107,41 +493,43 @@ function sanitizeUploadFileName(name) {
|
|
|
107
493
|
async function validateUploadFile(file, fieldName = "file", policy = DEFAULT_UPLOAD_POLICY) {
|
|
108
494
|
if (!Number.isSafeInteger(policy.maxBytes) || policy.maxBytes <= 0)
|
|
109
495
|
throw new RangeError("Upload limit must be a positive safe integer.");
|
|
496
|
+
if (typeof policy.allowUnknownMime !== "boolean")
|
|
497
|
+
throw new TypeError("Upload allowUnknownMime must be a boolean.");
|
|
110
498
|
if (!(file instanceof File)) {
|
|
111
|
-
throw new
|
|
499
|
+
throw new BadRequestError3(`Missing upload field "${fieldName}".`);
|
|
112
500
|
}
|
|
113
501
|
if (file.size <= 0) {
|
|
114
|
-
throw new
|
|
502
|
+
throw new BadRequestError3("Uploaded file is empty.");
|
|
115
503
|
}
|
|
116
504
|
const maxBytes = policy.maxBytes;
|
|
117
505
|
if (file.size > maxBytes) {
|
|
118
|
-
throw new
|
|
506
|
+
throw new PayloadTooLargeError2(`Upload exceeds the ${maxBytes} byte limit.`);
|
|
119
507
|
}
|
|
120
|
-
const mimeType =
|
|
508
|
+
const mimeType = normalizeMimeType3(file.type.trim() || "application/octet-stream");
|
|
121
509
|
if (!isAllowedMimeType(mimeType, policy.allowUnknownMime)) {
|
|
122
|
-
throw new
|
|
510
|
+
throw new BadRequestError3(`File type "${mimeType}" is not allowed.`);
|
|
123
511
|
}
|
|
512
|
+
const contents = new Uint8Array(await file.arrayBuffer());
|
|
513
|
+
assertUploadContentType(contents.subarray(0, 12), mimeType);
|
|
514
|
+
const decoder = uploadTextDecoder(mimeType);
|
|
515
|
+
validateUploadText(decoder, contents);
|
|
516
|
+
validateUploadText(decoder);
|
|
124
517
|
return {
|
|
125
518
|
fileName: sanitizeUploadFileName(file.name),
|
|
126
519
|
mimeType,
|
|
127
520
|
size: file.size,
|
|
128
|
-
contents
|
|
521
|
+
contents
|
|
129
522
|
};
|
|
130
523
|
}
|
|
131
524
|
async function parseMultipartUpload(request, fieldName = "file", policy = DEFAULT_UPLOAD_POLICY) {
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
}
|
|
136
|
-
const formData = await request.formData();
|
|
137
|
-
const value = formData.get(fieldName);
|
|
138
|
-
if (!(value instanceof File)) {
|
|
139
|
-
throw new BadRequestError(`Missing upload field "${fieldName}".`);
|
|
140
|
-
}
|
|
141
|
-
return validateUploadFile(value, fieldName, policy);
|
|
525
|
+
const file = await parseMultipartUploadStream(request, fieldName, policy);
|
|
526
|
+
const contents = await file.bytes();
|
|
527
|
+
return { fileName: file.fileName, mimeType: file.mimeType, size: contents.byteLength, contents };
|
|
142
528
|
}
|
|
143
529
|
export {
|
|
530
|
+
UploadedFile,
|
|
144
531
|
parseMultipartUpload,
|
|
532
|
+
parseMultipartUploadStream,
|
|
145
533
|
sanitizeUploadFileName,
|
|
146
534
|
validateUploadFile
|
|
147
535
|
};
|
|
@@ -3,6 +3,13 @@
|
|
|
3
3
|
var IMAGE_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
|
|
4
4
|
var MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
5
5
|
var MAX_IMAGE_PIXELS = 4096 * 4096;
|
|
6
|
+
var MAX_IMAGE_DIMENSION = 4096;
|
|
7
|
+
var CONTENT_TYPES = {
|
|
8
|
+
jpeg: "image/jpeg",
|
|
9
|
+
png: "image/png",
|
|
10
|
+
webp: "image/webp",
|
|
11
|
+
gif: "image/gif"
|
|
12
|
+
};
|
|
6
13
|
function normalizeMimeType(mimeType) {
|
|
7
14
|
return mimeType.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
8
15
|
}
|
|
@@ -13,39 +20,122 @@ function parseThumbnailWidth(raw, options = {}) {
|
|
|
13
20
|
const defaultWidth = options.defaultWidth ?? 200;
|
|
14
21
|
const minWidth = options.minWidth ?? 16;
|
|
15
22
|
const maxWidth = options.maxWidth ?? 800;
|
|
16
|
-
if (!raw?.trim())
|
|
23
|
+
if (!raw?.trim())
|
|
17
24
|
return defaultWidth;
|
|
18
|
-
}
|
|
19
25
|
const parsed = Number.parseInt(raw, 10);
|
|
20
|
-
if (!Number.isInteger(parsed))
|
|
26
|
+
if (!Number.isInteger(parsed))
|
|
21
27
|
return defaultWidth;
|
|
22
|
-
}
|
|
23
28
|
return Math.min(maxWidth, Math.max(minWidth, parsed));
|
|
24
29
|
}
|
|
25
|
-
|
|
26
|
-
if (
|
|
27
|
-
throw new
|
|
30
|
+
function dimension(value) {
|
|
31
|
+
if (!Number.isInteger(value) || value < 1 || value > MAX_IMAGE_DIMENSION)
|
|
32
|
+
throw new TypeError(`Image dimensions must be integers from 1 through ${MAX_IMAGE_DIMENSION}.`);
|
|
33
|
+
}
|
|
34
|
+
function transformOptions(input) {
|
|
35
|
+
if (!input || typeof input !== "object" || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
|
|
36
|
+
throw new TypeError("Invalid image transform options.");
|
|
37
|
+
const values = {};
|
|
38
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
39
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
40
|
+
if (typeof key !== "string" || ![
|
|
41
|
+
"width",
|
|
42
|
+
"height",
|
|
43
|
+
"fit",
|
|
44
|
+
"format",
|
|
45
|
+
"quality",
|
|
46
|
+
"withoutEnlargement",
|
|
47
|
+
"contentType"
|
|
48
|
+
].includes(key) || !descriptor || !("value" in descriptor))
|
|
49
|
+
throw new TypeError("Invalid image transform options.");
|
|
50
|
+
values[key] = descriptor.value;
|
|
28
51
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (
|
|
34
|
-
throw new
|
|
52
|
+
if (values.width !== undefined)
|
|
53
|
+
dimension(values.width);
|
|
54
|
+
if (values.height !== undefined)
|
|
55
|
+
dimension(values.height);
|
|
56
|
+
if (values.fit !== undefined && values.fit !== "inside" && values.fit !== "fill")
|
|
57
|
+
throw new TypeError("Image fit must be inside or fill.");
|
|
58
|
+
if (values.format !== undefined && !["jpeg", "png", "webp"].includes(values.format))
|
|
59
|
+
throw new TypeError("Image output format must be jpeg, png, or webp.");
|
|
60
|
+
if (values.quality !== undefined && (!Number.isInteger(values.quality) || values.quality < 1 || values.quality > 100))
|
|
61
|
+
throw new TypeError("Image quality must be an integer from 1 through 100.");
|
|
62
|
+
if (values.withoutEnlargement !== undefined && typeof values.withoutEnlargement !== "boolean")
|
|
63
|
+
throw new TypeError("Image withoutEnlargement must be a boolean.");
|
|
64
|
+
if (values.contentType !== undefined) {
|
|
65
|
+
if (typeof values.contentType !== "string" || !isImageMimeType(values.contentType))
|
|
66
|
+
throw new TypeError("Unsupported image content type.");
|
|
67
|
+
values.contentType = normalizeMimeType(values.contentType);
|
|
35
68
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
69
|
+
return values;
|
|
70
|
+
}
|
|
71
|
+
function imageFailure(error) {
|
|
72
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ERR_IMAGE_TOO_MANY_PIXELS")
|
|
73
|
+
return new Error("Image exceeds the maximum allowed dimensions.", { cause: error });
|
|
74
|
+
return new Error("Invalid or unsupported image contents.", { cause: error });
|
|
75
|
+
}
|
|
76
|
+
async function transformImageContents(contents, options = {}) {
|
|
77
|
+
const settings = transformOptions(options);
|
|
78
|
+
if (!(contents instanceof Uint8Array) || contents.byteLength === 0)
|
|
79
|
+
throw new TypeError("Image contents must be a nonempty Uint8Array.");
|
|
80
|
+
if (contents.byteLength > MAX_IMAGE_BYTES)
|
|
81
|
+
throw new Error("Image exceeds the maximum allowed size.");
|
|
82
|
+
const source = new Bun.Image(contents.slice(), { maxPixels: MAX_IMAGE_PIXELS });
|
|
83
|
+
let metadata;
|
|
84
|
+
try {
|
|
85
|
+
metadata = await source.metadata();
|
|
86
|
+
} catch (error) {
|
|
87
|
+
throw imageFailure(error);
|
|
88
|
+
}
|
|
89
|
+
if (!(metadata.format in CONTENT_TYPES))
|
|
90
|
+
throw new TypeError("Unsupported image input format.");
|
|
91
|
+
const detected = metadata.format;
|
|
92
|
+
if (settings.contentType !== undefined && settings.contentType !== CONTENT_TYPES[detected])
|
|
93
|
+
throw new TypeError("Image content type does not match its contents.");
|
|
94
|
+
const format = settings.format ?? (detected === "gif" ? "jpeg" : detected);
|
|
95
|
+
if (format === "png" && settings.quality !== undefined)
|
|
96
|
+
throw new TypeError("Image quality is supported only for jpeg and webp output.");
|
|
97
|
+
if (settings.width !== undefined || settings.height !== undefined) {
|
|
98
|
+
const width = settings.width ?? Math.max(1, Math.round(metadata.width * settings.height / metadata.height));
|
|
99
|
+
const height = settings.height ?? Math.max(1, Math.round(metadata.height * width / metadata.width));
|
|
100
|
+
dimension(width);
|
|
101
|
+
dimension(height);
|
|
102
|
+
source.resize(width, height, {
|
|
103
|
+
fit: settings.fit ?? "inside",
|
|
104
|
+
withoutEnlargement: settings.withoutEnlargement ?? true
|
|
105
|
+
});
|
|
106
|
+
} else {
|
|
107
|
+
dimension(metadata.width);
|
|
108
|
+
dimension(metadata.height);
|
|
39
109
|
}
|
|
40
|
-
if (
|
|
41
|
-
|
|
110
|
+
if (format === "png")
|
|
111
|
+
source.png();
|
|
112
|
+
else if (format === "webp")
|
|
113
|
+
source.webp({ quality: settings.quality });
|
|
114
|
+
else
|
|
115
|
+
source.jpeg({ quality: settings.quality });
|
|
116
|
+
let body;
|
|
117
|
+
try {
|
|
118
|
+
body = await source.bytes();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
throw imageFailure(error);
|
|
42
121
|
}
|
|
43
|
-
|
|
122
|
+
if (body.byteLength > MAX_IMAGE_BYTES)
|
|
123
|
+
throw new Error("Image output exceeds the maximum allowed size.");
|
|
124
|
+
return { body, contentType: CONTENT_TYPES[format], width: source.width, height: source.height };
|
|
125
|
+
}
|
|
126
|
+
async function resizeImageContents(contents, width, mimeType) {
|
|
127
|
+
const normalized = normalizeMimeType(mimeType);
|
|
128
|
+
return transformImageContents(contents, {
|
|
129
|
+
width,
|
|
130
|
+
format: normalized === "image/png" ? "png" : normalized === "image/webp" ? "webp" : "jpeg",
|
|
131
|
+
withoutEnlargement: false
|
|
132
|
+
});
|
|
44
133
|
}
|
|
45
134
|
export {
|
|
46
135
|
IMAGE_MIME_TYPES,
|
|
47
136
|
isImageMimeType,
|
|
48
137
|
normalizeMimeType,
|
|
49
138
|
parseThumbnailWidth,
|
|
50
|
-
resizeImageContents
|
|
139
|
+
resizeImageContents,
|
|
140
|
+
transformImageContents
|
|
51
141
|
};
|
|
@@ -21,18 +21,20 @@ export { CORE_JSON_RESPONSE_POLICY_TOKEN, CORE_MAIL_TOKEN, CORE_STORAGE_TOKEN, C
|
|
|
21
21
|
export type { TransactionAcquisitionMetrics, TransactionAcquisitionSnapshot, } from "@getstrata/core/database/acquisitionMetrics";
|
|
22
22
|
export { createTransactionAcquisitionMetrics, renderTransactionAcquisitionMetrics, } from "@getstrata/core/database/acquisitionMetrics";
|
|
23
23
|
export type { AfterCommitRepositoryContext, AfterCommitRepositoryListener, BoundModel, ModelBinding, ModelDefinition, ModelObserver, ModelState, RepositoryBinding, RepositoryDefinition, RepositoryEffectsDeclaration, RepositoryHooks, TransactionalRepositoryListener, TypedRepositoryEffect, } from "@getstrata/core/database/definitions";
|
|
24
|
-
export {
|
|
24
|
+
export { defineRepository, modelEffects, repositoryEffects, } from "@getstrata/core/database/definitions";
|
|
25
25
|
export type { PersistenceErrorCode, PersistenceErrorOptions, PersistenceResult, TransactionDataDisposition, } from "@getstrata/core/database/errors";
|
|
26
26
|
export { mapDatabaseError, PersistenceError, RecordNotFoundError, withDatabaseErrorHandling, } from "@getstrata/core/database/errors";
|
|
27
27
|
export type { FactoryBehavior, FactoryConstruction, FactoryDefinition, FactoryMakeResult, FactoryParent, FactoryPersist, StatelessFactoryConstruction, } from "@getstrata/core/database/factory";
|
|
28
28
|
export { defineFactory, Factory } from "@getstrata/core/database/factory";
|
|
29
|
+
export type { AnyModelClass, AuthoredModelClass, InferModelFields, ModelClassOptions, ModelField, ModelFields, } from "@getstrata/core/database/model";
|
|
29
30
|
export { DATABASE_SESSION_TOKEN } from "@getstrata/core/database/tokens";
|
|
30
31
|
export { BadRequestError, ConflictError, ForbiddenError, HttpError, InternalServerError, InvalidCredentialsError, isHttpErrorLike, NotFoundError, PayloadTooLargeError, PreconditionFailedError, toHttpError, UnauthorizedError, UnprocessableEntityError, ValidationError, } from "@getstrata/core/errors/http";
|
|
32
|
+
export { type ParsedUpload, parseMultipartUpload, parseMultipartUploadStream, sanitizeUploadFileName, UploadedFile, validateUploadFile, } from "@getstrata/core/http/parseMultipartUpload";
|
|
31
33
|
export type { RouteModelAuthorization, RouteModelBindingPorts, } from "@getstrata/core/http/securedRouteModelBinding";
|
|
32
34
|
export type { QueueHandoff, QueueIdentity } from "@getstrata/core/queue/queueHandoff";
|
|
33
35
|
export { createIdentityQueue, createQueueHandoff, QueueHandoffError, } from "@getstrata/core/queue/queueHandoff";
|
|
34
36
|
export { CORE_VIEW_RENDERER_TOKEN, CORE_WEB_ERROR_VIEW_TOKEN } from "@getstrata/core/view/tokens";
|
|
35
|
-
export { BaseRepository, BelongsToManyRelationQuery, BelongsToRelationQuery, createModel, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, Model, ModelQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, RepositoryQuery, } from "#strata-orm-runtime";
|
|
37
|
+
export { BaseRepository, BelongsToManyRelationQuery, BelongsToRelationQuery, createModel, defineModel, field, HasManyRelationQuery, HasManyThroughRelationQuery, HasOneRelationQuery, Model, ModelQuery, MorphManyRelationQuery, MorphOneRelationQuery, MorphToRelationQuery, modelTable, RepositoryQuery, } from "#strata-orm-runtime";
|
|
36
38
|
export type { AdminColumn, AdminColumnType, AdminResource, AdminResourceDefinition, AdminResourceHandlers, } from "../core/admin/index.ts";
|
|
37
39
|
export { AdminResourceRegistry, formatAdminValue, } from "../core/admin/index.ts";
|
|
38
40
|
export type { AbilityChecker } from "../core/auth/abilityChecker.ts";
|
|
@@ -120,7 +122,6 @@ export type { DisposableMemoryThrottle, MemoryThrottleOptions, MemoryThrottleSta
|
|
|
120
122
|
export { createMemoryThrottleMiddleware } from "../core/http/memoryThrottleMiddleware.ts";
|
|
121
123
|
export { createMetricsMiddleware } from "../core/http/metricsMiddleware.ts";
|
|
122
124
|
export type { Middleware, RouteHandler } from "../core/http/middleware.ts";
|
|
123
|
-
export { type ParsedUpload, parseMultipartUpload, sanitizeUploadFileName, validateUploadFile, } from "../core/http/parseMultipartUpload.ts";
|
|
124
125
|
export type { RequestMeta } from "../core/http/requestMetaContext.ts";
|
|
125
126
|
export { currentRequestMeta, requestMetaContext, resolveRequestId, runWithRequestMeta, } from "../core/http/requestMetaContext.ts";
|
|
126
127
|
export { createRequireAbilityMiddleware } from "../core/http/requireAbilityMiddleware.ts";
|