mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-07-17 10:06:17 +08:00
2f6c4e3696
Co-authored-by: Hongtao Lye <codert.sn@gmail.com> Co-authored-by: liuyi <forehalo@gmail.com> Co-authored-by: LongYinan <lynweklm@gmail.com> Co-authored-by: X1a0t <405028157@qq.com> Co-authored-by: JimmFly <yangjinfei001@gmail.com> Co-authored-by: Peng Xiao <pengxiao@outlook.com> Co-authored-by: xiaodong zuo <53252747+zuoxiaodong0815@users.noreply.github.com> Co-authored-by: DarkSky <25152247+darkskygit@users.noreply.github.com> Co-authored-by: Qi <474021214@qq.com> Co-authored-by: danielchim <kahungchim@gmail.com>
74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
const ALLOW_ORIGIN = [
|
|
'https://affine.pro',
|
|
'https://app.affine.pro',
|
|
'https://ambassador.affine.pro',
|
|
'https://affine.fail',
|
|
];
|
|
|
|
function isString(s: any): boolean {
|
|
return typeof s === 'string' || s instanceof String;
|
|
}
|
|
|
|
function isOriginAllowed(
|
|
origin: string,
|
|
allowedOrigin: string | RegExp | Array<string | RegExp>
|
|
): boolean {
|
|
if (Array.isArray(allowedOrigin)) {
|
|
for (let i = 0; i < allowedOrigin.length; ++i) {
|
|
if (isOriginAllowed(origin, allowedOrigin[i])) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
} else if (isString(allowedOrigin)) {
|
|
return origin === allowedOrigin;
|
|
} else if (allowedOrigin instanceof RegExp) {
|
|
return allowedOrigin.test(origin);
|
|
} else {
|
|
return !!allowedOrigin;
|
|
}
|
|
}
|
|
|
|
async function proxyImage(request: Request): Promise<Response> {
|
|
const url = new URL(request.url);
|
|
const imageURL = url.searchParams.get('url');
|
|
|
|
if (!imageURL) {
|
|
return new Response('Missing "url" parameter', { status: 400 });
|
|
}
|
|
|
|
const imageRequest = new Request(imageURL, {
|
|
method: 'GET',
|
|
headers: request.headers,
|
|
});
|
|
|
|
const response = await fetch(imageRequest);
|
|
const modifiedResponse = new Response(response.body);
|
|
|
|
modifiedResponse.headers.set(
|
|
'Access-Control-Allow-Origin',
|
|
request.headers.get('Origin') ?? 'null'
|
|
);
|
|
modifiedResponse.headers.set('Vary', 'Origin');
|
|
modifiedResponse.headers.set('Access-Control-Allow-Methods', 'GET');
|
|
|
|
return modifiedResponse;
|
|
}
|
|
|
|
const handler = {
|
|
async fetch(request: Request) {
|
|
if (!isOriginAllowed(request.headers.get('Origin') ?? '', ALLOW_ORIGIN)) {
|
|
return new Response('unauthorized', { status: 401 });
|
|
}
|
|
|
|
const url = new URL(request.url);
|
|
if (url.pathname.startsWith('/proxy/image')) {
|
|
return await proxyImage(request);
|
|
}
|
|
|
|
return new Response('not found', { status: 404 });
|
|
},
|
|
};
|
|
|
|
export default handler;
|