-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathextract_query_params.ts
82 lines (65 loc) · 2.69 KB
/
extract_query_params.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { StringEncrypter } from "@jmondi/string-encrypt-decrypt";
import { Context } from "hono";
import { HTTPException } from "hono/http-exception";
import { parseForm } from "zod-ff";
import { AppEnv } from "../app.js";
import { PlainConfigSchema } from "../lib/schema.js";
import { configToString, slugify } from "../lib/utils.js";
import { logger } from "../lib/logger.js";
export function handleExtractQueryParamsMiddleware(encryptionService?: StringEncrypter) {
return async (c: Context<AppEnv>, next: () => Promise<void>) => {
const params = new URL(c.req.url).searchParams;
let input: PlainConfigSchema | URLSearchParams;
if (params.has("hash")) {
if (!encryptionService) {
throw new HTTPException(400, { message: "This server is not configured for encryption" });
}
const hash = params.get("hash");
if (typeof hash !== "string" || !hash.startsWith("str-enc:")) {
throw new HTTPException(400, { message: "Invalid hash" });
}
const decryptedString = await encryptionService.decrypt(hash);
input = JSON.parse(decryptedString);
} else {
if (encryptionService) {
throw new HTTPException(400, { message: "This server must use encryption" });
}
input = params;
}
const { validData, errors } = parseForm({ data: input, schema: PlainConfigSchema });
if (validData?.viewPortWidth !== undefined) {
logger.warn("'viewPortWidth' is deprecated, please use 'viewportWidth'");
}
if (validData?.viewPortHeight !== undefined) {
logger.warn("'viewPortHeight' is deprecated, please use 'viewportHeight'");
}
if (errors) {
let message: string = "Invalid query parameters: ";
const specificErrors = Object.entries(errors)
.map(([key, value]) => `(${key} - ${value})`)
.join(" ");
message = `${message} ${specificErrors}`;
throw new HTTPException(400, { message, cause: errors });
}
if (validData.width && validData.width > 1920) {
validData.width = 1920;
}
if (validData.height && validData.height > 1920) {
validData.height = 1920;
}
const viewportWidth = validData.viewportWidth ?? validData.viewPortWidth;
if (viewportWidth && viewportWidth > 1920) {
validData.width = 1920;
}
const viewportHeight = validData.viewportHeight ?? validData.viewPortHeight;
if (viewportHeight && viewportHeight > 1920) {
validData.width = 1920;
}
const date = new Date();
const dateString = date.toLocaleDateString().replace(/\//g, "-");
const imageId = dateString + "." + slugify(validData.url) + configToString(params);
c.set("input", validData);
c.set("imageId", imageId);
await next();
};
}