Repository navigation
Expand file tree
/
Copy pathstorage-policy.ts
More file actions
158 lines (157 loc) · 5.34 KB
/
Copy pathstorage-policy.ts
File metadata and controls
158 lines (157 loc) · 5.34 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import { fileTypeFromBuffer, fileTypeFromFile } from "file-type";
import { open } from "node:fs/promises";
export const fileCategories = [
"image",
"video",
"audio",
"document",
"archive",
"other",
] as const;
export type FileCategory = (typeof fileCategories)[number];
export const uploadLimits = {
file: 2 * 1024 ** 3,
asset: 20 * 1024 ** 2,
profile: 5 * 1024 ** 2,
multipartThreshold: 32 * 1024 ** 2,
multipartPart: 8 * 1024 ** 2,
};
export function fileCategory(mime: string): FileCategory {
if (mime.startsWith("image/")) return "image";
if (mime.startsWith("video/")) return "video";
if (mime.startsWith("audio/")) return "audio";
if (/zip|gzip|rar|7z|tar|bzip|xz|zstd/.test(mime)) return "archive";
if (
mime.startsWith("text/") ||
/pdf|officedocument|msword|ms-excel|ms-powerpoint|opendocument|rtf|json|xml|yaml/.test(
mime,
)
)
return "document";
return "other";
}
const uuidPattern =
"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}";
export function objectKey(id: string, mime: string, namespace = "host") {
if (!new RegExp(`^${uuidPattern}$`).test(id))
throw new Error("Invalid object ID");
assertStorageNamespace(namespace);
return `${namespace}/objects/${fileCategory(mime)}/${id.slice(0, 2)}/${id.slice(2, 4)}/${id}/original`;
}
export function derivativeKey(
id: string,
mime: string,
recipe: string,
filename: string,
namespace = "host",
) {
if (
!/^[a-z0-9-]{1,40}$/.test(recipe) ||
!/^[a-z0-9-]+\.[a-z0-9]{1,8}$/.test(filename)
)
throw new Error("Invalid derivative path");
return objectKey(id, mime, namespace)
.replace("/objects/", "/derived/")
.replace(/original$/, `${recipe}/${filename}`);
}
export function validateObjectKey(key: string) {
if (new RegExp(`^host/knowledge-books/${uuidPattern}/${uuidPattern}/[a-f0-9]{64}\\.gz$`).test(key)) return;
if (new RegExp(`^host/document-history/${uuidPattern}/${uuidPattern}/[a-f0-9]{64}\\.json\\.gz$`).test(key)) return;
if (/^host\/plugin-releases\/[a-f0-9]{64}\.zip$/.test(key)) return;
if (
new RegExp(
`^plugins/[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*/objects/[1-9][0-9]*/${uuidPattern}/${uuidPattern}$`,
).test(key)
) {
assertStorageNamespace(key.split("/").slice(0, 2).join("/"));
return;
}
const namespace = storageNamespaceForKey(key);
const relative = key.slice(namespace.length + 1);
const match = new RegExp(
`^(objects|derived)/(${fileCategories.join("|")})/([a-f0-9]{2})/([a-f0-9]{2})/(${uuidPattern})/(original|[a-z0-9-]{1,40}/[a-z0-9-]+\\.[a-z0-9]{1,8})$`,
).exec(relative);
if (
!match ||
match[3] !== match[5]!.slice(0, 2) ||
match[4] !== match[5]!.slice(2, 4) ||
(match[1] === "objects") !== (match[6] === "original")
)
throw new Error("Invalid object key");
}
function assertStorageNamespace(namespace: string) {
if (namespace === "host") return;
const id = namespace.slice("plugins/".length);
if (
!namespace.startsWith("plugins/") ||
id.length > 100 ||
!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(id)
)
throw new Error("Invalid object key namespace");
}
export function storageNamespaceForKey(key: string) {
const namespace = key.startsWith("host/")
? "host"
: key.split("/").slice(0, 2).join("/");
assertStorageNamespace(namespace);
return namespace;
}
export function filePolicy(mime: string, size: number) {
const category = fileCategory(mime);
return {
category,
large: size >= uploadLimits.multipartThreshold,
upload: size >= uploadLimits.multipartThreshold ? "multipart" : "single",
// Only implemented processors are scheduled; video/audio retain originals.
thumbnail:
category === "image" &&
mime !== "image/svg+xml" &&
size <= uploadLimits.asset,
} as const;
}
const textMimes: Record<string, string> = {
txt: "text/plain",
log: "text/plain",
md: "text/markdown",
markdown: "text/markdown",
csv: "text/csv",
json: "application/json",
yaml: "text/yaml",
yml: "text/yaml",
xml: "application/xml",
html: "text/html",
htm: "text/html",
svg: "image/svg+xml",
};
function fallbackMime(sample: Buffer, filename: string) {
// Container signatures remain useful when an archive is incomplete/unrecognized.
if (sample.subarray(0, 4).equals(Buffer.from([0x50, 0x4b, 3, 4])))
return "application/zip";
try {
const text = new TextDecoder("utf-8", { fatal: true }).decode(sample, {
stream: true,
});
if (!/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(text)) {
const ext = filename.toLowerCase().split(".").pop()!;
if (ext === "svg" && !/<svg(?:\s|>)/i.test(text)) return "text/plain";
return textMimes[ext] ?? "text/plain";
}
} catch {}
return "application/octet-stream";
}
export async function detectBufferMime(data: Buffer, filename: string) {
const detected = await fileTypeFromBuffer(data).catch(() => undefined);
return detected?.mime ?? fallbackMime(data.subarray(0, 65536), filename);
}
export async function detectFileMime(path: string, filename: string) {
const detected = await fileTypeFromFile(path).catch(() => undefined);
if (detected) return detected.mime;
const handle = await open(path, "r");
try {
const sample = Buffer.alloc(65536);
const { bytesRead } = await handle.read(sample, 0, sample.length, 0);
return fallbackMime(sample.subarray(0, bytesRead), filename);
} finally {
await handle.close();
}
}