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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
|
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import * as fs from 'node:fs';
import sharp from 'sharp';
import { sharpBmp } from '@misskey-dev/sharp-read-bmp';
import type { Config } from '@/config.js';
import { FILE_TYPE_BROWSERSAFE } from '@/const.js';
import { StatusError } from '@/misc/status-error.js';
import { contentDisposition } from '@/misc/content-disposition.js';
import { correctFilename } from '@/misc/correct-filename.js';
import { isMimeImage } from '@/misc/is-mime-image.js';
import { IImageStreamable, ImageProcessingService, webpDefault } from '@/core/ImageProcessingService.js';
import { createRangeStream, attachStreamCleanup, needsCleanup } from './FileServerUtils.js';
import type { DownloadedFileResult, FileResolveResult, FileServerFileResolver } from './FileServerFileResolver.js';
import type { FastifyReply, FastifyRequest } from 'fastify';
type ProxySource = DownloadedFileResult | FileResolveResult;
type CleanupableFile = ProxySource & { cleanup: () => void };
type AvailableFile = Exclude<ProxySource, { kind: 'not-found' | 'unavailable' }>;
type ProxyQuery = {
emoji?: string;
avatar?: string;
static?: string;
preview?: string;
badge?: string;
origin?: string;
url?: string;
};
export class FileServerProxyHandler {
constructor(
private config: Config,
private fileResolver: FileServerFileResolver,
private assetsPath: string,
private imageProcessingService: ImageProcessingService,
) {}
public async handle(request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>, reply: FastifyReply) {
const url = 'url' in request.query ? request.query.url : 'https://' + request.params.url;
if (typeof url !== 'string') {
reply.code(400);
return;
}
// アバタークロップなど、どうしてもオリジンである必要がある場合
const mustOrigin = 'origin' in request.query;
if (this.config.externalMediaProxyEnabled && !mustOrigin) {
return await this.redirectToExternalProxy(request, reply);
}
this.validateUserAgent(request);
// Create temp file
const file = await this.getStreamAndTypeFromUrl(url);
if (file.kind === 'not-found') {
reply.code(404);
reply.header('Cache-Control', 'max-age=86400');
return reply.sendFile('/dummy.png', this.assetsPath);
}
if (file.kind === 'unavailable') {
reply.code(204);
reply.header('Cache-Control', 'max-age=86400');
return;
}
try {
const image = await this.processImage(file, request, reply);
if (needsCleanup(file)) {
attachStreamCleanup(image.data, file.cleanup);
}
reply.header('Content-Type', image.type);
reply.header('Cache-Control', 'max-age=31536000, immutable');
reply.header('Content-Disposition',
contentDisposition(
'inline',
correctFilename(file.filename, image.ext),
),
);
return image.data;
} catch (e) {
if (needsCleanup(file)) file.cleanup();
throw e;
}
}
/**
* 外部メディアプロキシにリダイレクトする
*/
private async redirectToExternalProxy(
request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>,
reply: FastifyReply,
) {
reply.header('Cache-Control', 'public, max-age=259200'); // 3 days
const url = new URL(`${this.config.mediaProxy}/${request.params.url || ''}`);
for (const [key, value] of Object.entries(request.query)) {
url.searchParams.append(key, value);
}
return reply.redirect(url.toString(), 301);
}
/**
* User-Agent を検証する
*/
private validateUserAgent(request: FastifyRequest): void {
if (!request.headers['user-agent']) {
throw new StatusError('User-Agent is required', 400, 'User-Agent is required');
}
if (request.headers['user-agent'].toLowerCase().indexOf('misskey/') !== -1) {
throw new StatusError('Refusing to proxy a request from another proxy', 403, 'Proxy is recursive');
}
}
/**
* 画像を処理してストリーム可能な形式に変換する
*/
private async processImage(
file: AvailableFile,
request: FastifyRequest<{ Params: { url: string }; Querystring: ProxyQuery }>,
reply: FastifyReply,
): Promise<IImageStreamable> {
const query = request.query;
const requiresImageConversion = 'emoji' in query || 'avatar' in query || 'static' in query || 'preview' in query || 'badge' in query;
const isConvertibleImage = isMimeImage(file.mime, 'sharp-convertible-image-with-bmp');
if (requiresImageConversion && !isConvertibleImage) {
throw new StatusError('Unexpected mime', 404);
}
if ('emoji' in query || 'avatar' in query) {
return this.processEmojiOrAvatar(file, query);
}
if ('static' in query) {
return this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 498, 422);
}
if ('preview' in query) {
return this.imageProcessingService.convertSharpToWebpStream(await sharpBmp(file.path, file.mime), 200, 200);
}
if ('badge' in query) {
return this.processBadge(file);
}
if (file.mime === 'image/svg+xml') {
return this.imageProcessingService.convertToWebpStream(file.path, 2048, 2048);
}
if (!file.mime.startsWith('image/') || !FILE_TYPE_BROWSERSAFE.includes(file.mime)) {
throw new StatusError('Rejected type', 403, 'Rejected type');
}
return this.createDefaultStream(file, request, reply);
}
/**
* 絵文字またはアバター用の画像を処理する
*/
private async processEmojiOrAvatar(
file: AvailableFile,
query: Pick<ProxyQuery, 'emoji' | 'avatar' | 'static'>,
): Promise<IImageStreamable> {
const isAnimationConvertibleImage = isMimeImage(file.mime, 'sharp-animation-convertible-image-with-bmp');
if (!isAnimationConvertibleImage && !('static' in query)) {
return {
data: fs.createReadStream(file.path),
ext: file.ext,
type: file.mime,
};
}
const data = (await sharpBmp(file.path, file.mime, { animated: !('static' in query) }))
.resize({
height: 'emoji' in query ? 128 : 320,
withoutEnlargement: true,
})
.webp(webpDefault);
return {
data,
ext: 'webp',
type: 'image/webp',
};
}
/**
* バッジ用の画像を処理する
*/
private async processBadge(file: AvailableFile): Promise<IImageStreamable> {
const mask = (await sharpBmp(file.path, file.mime))
.resize(96, 96, {
fit: 'contain',
position: 'centre',
withoutEnlargement: false,
})
.greyscale()
.normalise()
.linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast
.flatten({ background: '#000' })
.toColorspace('b-w');
const stats = await mask.clone().stats();
if (stats.entropy < 0.1) {
throw new StatusError('Skip to provide badge', 404);
}
const data = sharp({
create: { width: 96, height: 96, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
})
.pipelineColorspace('b-w')
.boolean(await mask.png().toBuffer(), 'eor');
return {
data: await data.png().toBuffer(),
ext: 'png',
type: 'image/png',
};
}
/**
* デフォルトのストリームを作成する(Range リクエスト対応)
*/
private createDefaultStream(
file: AvailableFile,
request: FastifyRequest,
reply: FastifyReply,
): IImageStreamable {
if (request.headers.range && 'file' in file && file.file.size > 0) {
const { stream, start, end, chunksize } = createRangeStream(request.headers.range as string, file.file.size, file.path);
reply.header('Content-Range', `bytes ${start}-${end}/${file.file.size}`);
reply.header('Accept-Ranges', 'bytes');
reply.header('Content-Length', chunksize);
reply.code(206);
return {
data: stream,
ext: file.ext,
type: file.mime,
};
}
return {
data: fs.createReadStream(file.path),
ext: file.ext,
type: file.mime,
};
}
private async getStreamAndTypeFromUrl(url: string): Promise<ProxySource> {
if (url.startsWith(`${this.config.webUrl}/files/`)) {
const key = url.replace(`${this.config.webUrl}/files/`, '').split('/').shift();
if (!key) throw new StatusError('Invalid File Key', 400, 'Invalid File Key');
return await this.fileResolver.resolveFileByAccessKey(key);
}
return await this.fileResolver.downloadAndDetectTypeFromUrl(url);
}
}
|