mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-03 18:40:05 +03:00
fix(core): fix self-hosted image proxy and link preview (#16009)
Configure `ImageProxyService` in `AffineLinkPreviewExtension`, make its URL reactive, and add `crossorigin="anonymous"` to image-proxy images. Add an Electron `Referer` header for internal `assets://` worker requests. Normalize custom-scheme and IP origins in `worker.allowedOrigin`, and allow `x-affine-client-kind` in link-preview CORS preflight responses. Closes #14865 Co-authored-by: DarkSky <darksky2048@gmail.com>
This commit is contained in:
1 parent
7e27087a53
commit
4e5ed5af8a
30 files changed
+886
-82
No files matched your search
@@ -70,7 +70,11 @@ export class BookmarkCard extends SignalWatcher(
|
||||
const titleIcon = this.loading
|
||||
? LoadingIcon()
|
||||
: icon
|
||||
? html`<img src=${imageProxyService.buildUrl(icon)} alt="icon" />`
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(icon)}
|
||||
alt="icon"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: WebIcon16;
|
||||
|
||||
const descriptionText = this.loading
|
||||
@@ -83,7 +87,11 @@ export class BookmarkCard extends SignalWatcher(
|
||||
|
||||
const bannerImage =
|
||||
!this.loading && image
|
||||
? html`<img src=${imageProxyService.buildUrl(image)} alt="banner" />`
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(image)}
|
||||
alt="banner"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: EmbedCardBannerIcon;
|
||||
|
||||
return html`
|
||||
|
||||
@@ -143,7 +143,11 @@ export class EmbedGithubBlockComponent extends EmbedBlockComponent<
|
||||
const descriptionText = loading ? '' : description;
|
||||
const bannerImage =
|
||||
!loading && image
|
||||
? html`<img src=${imageProxyService.buildUrl(image)} alt="banner" />`
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(image)}
|
||||
alt="banner"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: EmbedCardBannerIcon;
|
||||
|
||||
let dateText = '';
|
||||
|
||||
@@ -100,7 +100,11 @@ export class EmbedLoomBlockComponent extends EmbedBlockComponent<
|
||||
const descriptionText = loading ? '' : description;
|
||||
const bannerImage =
|
||||
!loading && image
|
||||
? html`<img src=${imageProxyService.buildUrl(image)} alt="banner" />`
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(image)}
|
||||
alt="banner"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: EmbedCardBannerIcon;
|
||||
|
||||
return this.renderEmbed(
|
||||
|
||||
@@ -101,7 +101,11 @@ export class EmbedYoutubeBlockComponent extends EmbedBlockComponent<
|
||||
const descriptionText = loading ? null : description;
|
||||
const bannerImage =
|
||||
!loading && image
|
||||
? html`<img src=${imageProxyService.buildUrl(image)} alt="banner" />`
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(image)}
|
||||
alt="banner"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: EmbedCardBannerIcon;
|
||||
|
||||
const creatorImageEl =
|
||||
@@ -109,6 +113,7 @@ export class EmbedYoutubeBlockComponent extends EmbedBlockComponent<
|
||||
? html`<img
|
||||
src=${imageProxyService.buildUrl(creatorImage)}
|
||||
alt="creator"
|
||||
crossorigin="anonymous"
|
||||
/>`
|
||||
: nothing;
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { ImageBlockModel, type RootBlockModel } from '@blocksuite/affine-model';
|
||||
import { FetchUtils } from '@blocksuite/affine-shared/adapters';
|
||||
import {
|
||||
FetchUtils,
|
||||
ImageProxyService,
|
||||
} from '@blocksuite/affine-shared/adapters';
|
||||
import {
|
||||
CANVAS_EXPORT_IGNORE_TAGS,
|
||||
DEFAULT_IMAGE_PROXY_ENDPOINT,
|
||||
@@ -45,15 +48,18 @@ export class ExportManager {
|
||||
imageProxyEndpoint: DEFAULT_IMAGE_PROXY_ENDPOINT,
|
||||
};
|
||||
|
||||
private get _imageProxyEndpoint() {
|
||||
return (
|
||||
this.std.getOptional(ImageProxyService)?.imageProxyURL ??
|
||||
this._exportOptions.imageProxyEndpoint
|
||||
);
|
||||
}
|
||||
|
||||
replaceImgSrcWithSvg = async (element: HTMLElement) => {
|
||||
const imgList = Array.from(element.querySelectorAll('img'));
|
||||
// Create an array of promises
|
||||
const promises = imgList.map(img => {
|
||||
return FetchUtils.fetchImage(
|
||||
img.src,
|
||||
undefined,
|
||||
this._exportOptions.imageProxyEndpoint
|
||||
)
|
||||
return FetchUtils.fetchImage(img.src, undefined, this._imageProxyEndpoint)
|
||||
.then(response => response && response.blob())
|
||||
.then(async blob => {
|
||||
if (!blob) return;
|
||||
@@ -225,8 +231,8 @@ export class ExportManager {
|
||||
x: pageLeft - viewport.left,
|
||||
width: pageWidth,
|
||||
height: viewportHeight,
|
||||
useCORS: this._exportOptions.imageProxyEndpoint ? false : true,
|
||||
proxy: this._exportOptions.imageProxyEndpoint,
|
||||
useCORS: this._imageProxyEndpoint ? false : true,
|
||||
proxy: this._imageProxyEndpoint,
|
||||
};
|
||||
|
||||
let data: HTMLCanvasElement;
|
||||
@@ -322,8 +328,8 @@ export class ExportManager {
|
||||
|
||||
await this.replaceImgSrcWithSvg(element);
|
||||
},
|
||||
useCORS: this._exportOptions.imageProxyEndpoint ? false : true,
|
||||
proxy: this._exportOptions.imageProxyEndpoint,
|
||||
useCORS: this._imageProxyEndpoint ? false : true,
|
||||
proxy: this._imageProxyEndpoint,
|
||||
};
|
||||
|
||||
let data: HTMLCanvasElement;
|
||||
|
||||
@@ -109,7 +109,7 @@ export class CitationCard extends SignalWatcher(WithDisposable(LitElement)) {
|
||||
|
||||
private readonly _IconTemplate = (icon: TemplateResult | string) => {
|
||||
if (typeof icon === 'string') {
|
||||
return html`<img src="${icon}" alt="favicon" />`;
|
||||
return html`<img src="${icon}" alt="favicon" crossorigin="anonymous" />`;
|
||||
}
|
||||
return icon;
|
||||
};
|
||||
|
||||
@@ -83,7 +83,9 @@ export class FootNotePopup extends SignalWatcher(WithDisposable(LitElement)) {
|
||||
const imageSrc = favicon
|
||||
? this.imageProxyService.buildUrl(favicon)
|
||||
: undefined;
|
||||
return imageSrc ? html`<img src=${imageSrc} alt="favicon" />` : WebIcon16;
|
||||
return imageSrc
|
||||
? html`<img src=${imageSrc} alt="favicon" crossorigin="anonymous" />`
|
||||
: WebIcon16;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { effect } from '@preact/signals-core';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
ImageProxyService,
|
||||
isImageProxyURL,
|
||||
} from '../../../adapters/middlewares/proxy';
|
||||
|
||||
describe('ImageProxyService', () => {
|
||||
it('notifies signal observers when setImageProxyURL updates the endpoint', () => {
|
||||
const service = new ImageProxyService({} as never);
|
||||
const urls: string[] = [];
|
||||
|
||||
const dispose = effect(() => {
|
||||
urls.push(service.buildUrl('https://example.com/icon.png'));
|
||||
});
|
||||
|
||||
service.setImageProxyURL(
|
||||
'https://selfhosted.example/api/worker/image-proxy'
|
||||
);
|
||||
dispose();
|
||||
|
||||
expect(urls).toHaveLength(2);
|
||||
expect(urls[1]).toBe(
|
||||
'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Ficon.png'
|
||||
);
|
||||
});
|
||||
|
||||
it('recognizes relative image proxy URLs even when location.origin is opaque null', () => {
|
||||
const originalLocation = globalThis.location;
|
||||
vi.stubGlobal('location', { origin: 'null' });
|
||||
try {
|
||||
expect(
|
||||
isImageProxyURL(
|
||||
'/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png'
|
||||
)
|
||||
).toBe(true);
|
||||
} finally {
|
||||
vi.stubGlobal('location', originalLocation);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { TransformerMiddleware } from '@blocksuite/store';
|
||||
import { StoreExtension } from '@blocksuite/store';
|
||||
import { signal } from '@preact/signals-core';
|
||||
|
||||
import { DEFAULT_IMAGE_PROXY_ENDPOINT } from '../../consts';
|
||||
|
||||
@@ -25,7 +26,9 @@ const IMAGE_PROXY_PATH = '/api/worker/image-proxy';
|
||||
|
||||
export const isImageProxyURL = (imageUrl: string) => {
|
||||
try {
|
||||
const url = new URL(imageUrl, globalThis.location.origin);
|
||||
const origin = globalThis.location?.origin;
|
||||
const base = origin && origin !== 'null' ? origin : 'http://localhost';
|
||||
const url = new URL(imageUrl, base);
|
||||
return url.pathname === IMAGE_PROXY_PATH && url.searchParams.has('url');
|
||||
} catch {
|
||||
return false;
|
||||
@@ -44,10 +47,10 @@ export const defaultImageProxyMiddleware: TransformerMiddleware = args => {
|
||||
export class ImageProxyService extends StoreExtension {
|
||||
static override key = 'image-proxy';
|
||||
|
||||
private _imageProxyURL = DEFAULT_IMAGE_PROXY_ENDPOINT;
|
||||
private readonly _imageProxyURL$ = signal(DEFAULT_IMAGE_PROXY_ENDPOINT);
|
||||
|
||||
setImageProxyURL(url: string) {
|
||||
this._imageProxyURL = url;
|
||||
this._imageProxyURL$.value = url;
|
||||
setImageProxyMiddlewareURL(url);
|
||||
}
|
||||
|
||||
@@ -60,6 +63,6 @@ export class ImageProxyService extends StoreExtension {
|
||||
}
|
||||
|
||||
get imageProxyURL() {
|
||||
return this._imageProxyURL;
|
||||
return this._imageProxyURL$.value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import ava from 'ava';
|
||||
import type {
|
||||
Request as ExpressRequest,
|
||||
Response as ExpressResponse,
|
||||
} from 'express';
|
||||
|
||||
import { BadRequest, Config } from '../../../base';
|
||||
import { URLHelper } from '../../../base/helpers';
|
||||
import { WorkerController } from '../controller';
|
||||
import { WorkerService } from '../service';
|
||||
|
||||
const test = ava;
|
||||
|
||||
function createController(cachedValue?: string) {
|
||||
const config = Object.assign(new Config(), {
|
||||
server: {
|
||||
externalUrl: '',
|
||||
host: 'selfhosted.example',
|
||||
hosts: [],
|
||||
port: 3010,
|
||||
https: true,
|
||||
path: '',
|
||||
},
|
||||
worker: {
|
||||
allowedOrigin: [],
|
||||
},
|
||||
});
|
||||
const url = new URLHelper(config);
|
||||
const service = new WorkerService(config, url);
|
||||
service.onConfigInit();
|
||||
const cache = {
|
||||
get: async () => cachedValue,
|
||||
set: async () => {},
|
||||
};
|
||||
return new WorkerController(cache as any, url, service);
|
||||
}
|
||||
|
||||
function createMockResponse() {
|
||||
const headers = new Map<string, string>();
|
||||
let statusCode = 200;
|
||||
let body: unknown;
|
||||
const resp = {
|
||||
status(code: number) {
|
||||
statusCode = code;
|
||||
return resp;
|
||||
},
|
||||
header(entries: Record<string, string>) {
|
||||
for (const [key, value] of Object.entries(entries)) {
|
||||
headers.set(key.toLowerCase(), value);
|
||||
}
|
||||
return resp;
|
||||
},
|
||||
setHeader(key: string, value: string) {
|
||||
headers.set(key.toLowerCase(), value);
|
||||
return resp;
|
||||
},
|
||||
getHeader(key: string) {
|
||||
return headers.get(key.toLowerCase());
|
||||
},
|
||||
send(payload?: unknown) {
|
||||
body = payload;
|
||||
return resp;
|
||||
},
|
||||
};
|
||||
return {
|
||||
resp: resp as unknown as ExpressResponse,
|
||||
get statusCode() {
|
||||
return statusCode;
|
||||
},
|
||||
get body() {
|
||||
return body;
|
||||
},
|
||||
headers,
|
||||
};
|
||||
}
|
||||
|
||||
const PNG_1X1_BASE64 =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jfJ8AAAAASUVORK5CYII=';
|
||||
|
||||
test('allows client origins and custom-scheme referers on imageProxy while rejecting missing or untrusted headers', async t => {
|
||||
const controller = createController(PNG_1X1_BASE64);
|
||||
|
||||
const allowedCases: Array<{
|
||||
name: string;
|
||||
headers: Record<string, string>;
|
||||
expectedAcao?: string;
|
||||
}> = [
|
||||
{
|
||||
name: 'desktop Origin assets://.',
|
||||
headers: { origin: 'assets://.' },
|
||||
expectedAcao: 'assets://.',
|
||||
},
|
||||
{
|
||||
name: 'iOS Origin capacitor://localhost',
|
||||
headers: { origin: 'capacitor://localhost' },
|
||||
expectedAcao: 'capacitor://localhost',
|
||||
},
|
||||
{
|
||||
name: 'Android Origin https://localhost',
|
||||
headers: { origin: 'https://localhost' },
|
||||
expectedAcao: 'https://localhost',
|
||||
},
|
||||
{
|
||||
name: 'desktop Referer assets://./',
|
||||
headers: { referer: 'assets://./' },
|
||||
},
|
||||
{
|
||||
name: 'same-origin Web Referer',
|
||||
headers: { referer: 'https://selfhosted.example/workspace/1' },
|
||||
},
|
||||
];
|
||||
|
||||
for (const item of allowedCases) {
|
||||
const mockResp = createMockResponse();
|
||||
const req = {
|
||||
url: '/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
headers: item.headers,
|
||||
} as unknown as ExpressRequest;
|
||||
|
||||
await controller.imageProxy(req, mockResp.resp);
|
||||
t.is(mockResp.statusCode, 200, item.name);
|
||||
if (item.expectedAcao) {
|
||||
t.is(
|
||||
mockResp.headers.get('access-control-allow-origin'),
|
||||
item.expectedAcao,
|
||||
item.name
|
||||
);
|
||||
t.is(mockResp.headers.get('vary'), 'Origin', item.name);
|
||||
}
|
||||
}
|
||||
|
||||
const rejectedCases: Array<{
|
||||
name: string;
|
||||
headers: Record<string, string>;
|
||||
}> = [
|
||||
{ name: 'missing Origin and Referer', headers: {} },
|
||||
{
|
||||
name: 'untrusted Origin',
|
||||
headers: { origin: 'https://evil.example' },
|
||||
},
|
||||
{
|
||||
name: 'untrusted Referer',
|
||||
headers: { referer: 'https://evil.example/page' },
|
||||
},
|
||||
];
|
||||
|
||||
for (const item of rejectedCases) {
|
||||
const mockResp = createMockResponse();
|
||||
const req = {
|
||||
url: '/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
headers: item.headers,
|
||||
} as unknown as ExpressRequest;
|
||||
|
||||
await t.throwsAsync(
|
||||
() => controller.imageProxy(req, mockResp.resp),
|
||||
{ instanceOf: BadRequest, message: 'Invalid header' },
|
||||
item.name
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('allows x-affine-client-kind in linkPreview preflight CORS headers', t => {
|
||||
const controller = createController();
|
||||
const mockResp = createMockResponse();
|
||||
const req = {
|
||||
headers: { origin: 'capacitor://localhost' },
|
||||
} as unknown as ExpressRequest;
|
||||
|
||||
controller.linkPreviewOption(req, mockResp.resp);
|
||||
|
||||
t.is(mockResp.statusCode, 204);
|
||||
t.is(
|
||||
mockResp.headers.get('access-control-allow-origin'),
|
||||
'capacitor://localhost'
|
||||
);
|
||||
const allowedHeaders =
|
||||
mockResp.headers.get('access-control-allow-headers')?.toLowerCase() ?? '';
|
||||
t.true(allowedHeaders.includes('content-type'));
|
||||
t.true(allowedHeaders.includes('x-affine-version'));
|
||||
t.true(allowedHeaders.includes('x-affine-client-kind'));
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import ava from 'ava';
|
||||
|
||||
import { isRefererAllowed } from '../utils';
|
||||
import { isRefererAllowed, normalizeAllowedOrigin } from '../utils';
|
||||
|
||||
const test = ava;
|
||||
|
||||
@@ -29,3 +29,25 @@ test('rejects a custom-scheme referer that is not in the list', t => {
|
||||
t.false(isRefererAllowed('capacitor://evil.example/', allowed));
|
||||
t.false(isRefererAllowed('not a url', allowed));
|
||||
});
|
||||
|
||||
test('normalizes configured allowed origins across http(s), IP, bare host, and custom schemes', t => {
|
||||
t.is(
|
||||
normalizeAllowedOrigin('https://app.affine.local/workspace/1'),
|
||||
'https://app.affine.local'
|
||||
);
|
||||
t.is(
|
||||
normalizeAllowedOrigin('http://192.168.1.50:3010/path'),
|
||||
'http://192.168.1.50:3010'
|
||||
);
|
||||
t.is(normalizeAllowedOrigin('localhost'), 'http://localhost');
|
||||
t.is(normalizeAllowedOrigin('assets://.'), 'assets://.');
|
||||
t.is(normalizeAllowedOrigin('assets://./index.html'), 'assets://.');
|
||||
t.is(
|
||||
normalizeAllowedOrigin('capacitor://localhost/page'),
|
||||
'capacitor://localhost'
|
||||
);
|
||||
t.is(normalizeAllowedOrigin('file:///app/index.html'), 'file://');
|
||||
t.is(normalizeAllowedOrigin('javascript://evil.example'), null);
|
||||
t.is(normalizeAllowedOrigin('data:text/html,hi'), null);
|
||||
t.is(normalizeAllowedOrigin(' '), null);
|
||||
});
|
||||
@@ -18,7 +18,13 @@ test('allows global mobile origins and normalized configured origins only', t =>
|
||||
path: '',
|
||||
},
|
||||
worker: {
|
||||
allowedOrigin: ['http://preview.affine.local/path'],
|
||||
allowedOrigin: [
|
||||
'http://preview.affine.local/path',
|
||||
'assets://.',
|
||||
'custom-client://app/path',
|
||||
'http://192.168.1.50:3010/path',
|
||||
'javascript://evil.example',
|
||||
],
|
||||
},
|
||||
});
|
||||
const url = new URLHelper(config);
|
||||
@@ -26,10 +32,14 @@ test('allows global mobile origins and normalized configured origins only', t =>
|
||||
|
||||
service.onConfigInit();
|
||||
|
||||
t.true(isOriginAllowed('assets://.', service.allowedOrigins));
|
||||
t.true(isOriginAllowed('capacitor://localhost', service.allowedOrigins));
|
||||
t.true(isOriginAllowed('https://localhost', service.allowedOrigins));
|
||||
t.true(
|
||||
isOriginAllowed('http://preview.affine.local', service.allowedOrigins)
|
||||
);
|
||||
t.true(isOriginAllowed('custom-client://app', service.allowedOrigins));
|
||||
t.true(isOriginAllowed('http://192.168.1.50:3010', service.allowedOrigins));
|
||||
t.false(isOriginAllowed('javascript://evil.example', service.allowedOrigins));
|
||||
t.false(isOriginAllowed('https://unrelated.example', service.allowedOrigins));
|
||||
});
|
||||
@@ -262,7 +262,8 @@ export class WorkerController {
|
||||
.header({
|
||||
...getCorsHeaders(origin),
|
||||
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, x-affine-version',
|
||||
'Access-Control-Allow-Headers':
|
||||
'Content-Type, x-affine-version, x-affine-client-kind',
|
||||
})
|
||||
.send();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
OnEvent,
|
||||
URLHelper,
|
||||
} from '../../base';
|
||||
import { fixUrl, OriginRules } from './utils';
|
||||
import { normalizeAllowedOrigin, OriginRules } from './utils';
|
||||
|
||||
@Injectable()
|
||||
export class WorkerService {
|
||||
@@ -24,8 +24,8 @@ export class WorkerService {
|
||||
this.allowedOrigins = Array.from(
|
||||
new Set([
|
||||
...this.config.worker.allowedOrigin
|
||||
.map(u => fixUrl(u)?.origin as string)
|
||||
.filter(v => !!v),
|
||||
.map(u => normalizeAllowedOrigin(u))
|
||||
.filter((v): v is string => !!v),
|
||||
...buildCorsAllowedOrigins(this.url),
|
||||
])
|
||||
);
|
||||
|
||||
@@ -1,12 +1,57 @@
|
||||
import { IncomingHttpHeaders } from 'node:http';
|
||||
|
||||
import { fixUrl } from './url';
|
||||
|
||||
export type OriginRule = string | RegExp | ((origin: string) => boolean);
|
||||
export type OriginRules = OriginRule | OriginRule[];
|
||||
|
||||
const DISALLOWED_ORIGIN_SCHEMES = new Set([
|
||||
'javascript:',
|
||||
'data:',
|
||||
'vbscript:',
|
||||
'blob:',
|
||||
'about:',
|
||||
]);
|
||||
|
||||
function isString(s: OriginRule): s is string {
|
||||
return typeof s === 'string' || s instanceof String;
|
||||
}
|
||||
|
||||
export function extractOrigin(input: string): string | null {
|
||||
try {
|
||||
const url = new URL(input);
|
||||
// URL.origin is the opaque "null" for non-special schemes such as
|
||||
// assets:// (desktop), capacitor:// (mobile) and file://. Build the origin
|
||||
// the way a browser serializes it in an Origin header.
|
||||
return url.origin === 'null' ? `${url.protocol}//${url.host}` : url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeAllowedOrigin(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(trimmed)) {
|
||||
try {
|
||||
const url = new URL(trimmed);
|
||||
if (DISALLOWED_ORIGIN_SCHEMES.has(url.protocol)) {
|
||||
return null;
|
||||
}
|
||||
return url.origin === 'null'
|
||||
? `${url.protocol}//${url.host}`
|
||||
: url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return fixUrl(trimmed)?.origin ?? null;
|
||||
}
|
||||
|
||||
export function isOriginAllowed(origin: string, allowedOrigin: OriginRules) {
|
||||
if (Array.isArray(allowedOrigin)) {
|
||||
for (const allowed of allowedOrigin) {
|
||||
@@ -24,17 +69,8 @@ export function isOriginAllowed(origin: string, allowedOrigin: OriginRules) {
|
||||
}
|
||||
|
||||
export function isRefererAllowed(referer: string, allowedOrigin: OriginRules) {
|
||||
try {
|
||||
const url = new URL(referer);
|
||||
// URL.origin is the opaque "null" for non-special schemes such as
|
||||
// assets:// (desktop), capacitor:// (mobile) and file://. Build the origin
|
||||
// the way a browser serializes it in an Origin header.
|
||||
const origin =
|
||||
url.origin === 'null' ? `${url.protocol}//${url.host}` : url.origin;
|
||||
return isOriginAllowed(origin, allowedOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const origin = extractOrigin(referer);
|
||||
return origin ? isOriginAllowed(origin, allowedOrigin) : false;
|
||||
}
|
||||
|
||||
const headerFilters = [/^Sec-/i, /^Accept/i, /^User-Agent$/i];
|
||||
|
||||
@@ -3,7 +3,12 @@ import { pathToFileURL } from 'node:url';
|
||||
|
||||
import { app, net, protocol, session } from 'electron';
|
||||
|
||||
import { anotherHost, mainHost } from '../shared/internal-origin';
|
||||
import {
|
||||
anotherHost,
|
||||
anotherOrigin,
|
||||
mainHost,
|
||||
mainWindowOrigin,
|
||||
} from '../shared/internal-origin';
|
||||
import {
|
||||
isPathInsideBase,
|
||||
isWindows,
|
||||
@@ -154,6 +159,16 @@ const needRefererDomains = [
|
||||
/^(?:[a-zA-Z0-9-]+\.)*googlevideo\.com$/,
|
||||
];
|
||||
const defaultReferer = 'https://client.affine.local/';
|
||||
const workerEndpointPaths = new Set([
|
||||
'/api/worker/image-proxy',
|
||||
'/api/worker/link-preview',
|
||||
]);
|
||||
const internalOrigins = new Set([mainWindowOrigin, anotherOrigin]);
|
||||
|
||||
function hasHeader(headers: Record<string, string>, name: string) {
|
||||
const lower = name.toLowerCase();
|
||||
return Object.keys(headers).some(key => key.toLowerCase() === lower);
|
||||
}
|
||||
const affineDomains = [
|
||||
/^(?:[a-z0-9-]+\.)*usercontent\.affine\.pro$/i,
|
||||
/^(?:[a-z0-9-]+\.)*affine\.pro$/i,
|
||||
@@ -277,9 +292,21 @@ export async function registerProtocol() {
|
||||
const needReferer = needRefererDomains.some(regex =>
|
||||
regex.test(hostname)
|
||||
);
|
||||
if (needReferer && !details.requestHeaders['Referer']) {
|
||||
if (needReferer && !hasHeader(details.requestHeaders, 'Referer')) {
|
||||
details.requestHeaders['Referer'] = defaultReferer;
|
||||
}
|
||||
|
||||
const isHttp = url.protocol === 'http:' || url.protocol === 'https:';
|
||||
if (
|
||||
isHttp &&
|
||||
workerEndpointPaths.has(url.pathname) &&
|
||||
details.initiatorOrigin &&
|
||||
internalOrigins.has(details.initiatorOrigin) &&
|
||||
!hasHeader(details.requestHeaders, 'Origin') &&
|
||||
!hasHeader(details.requestHeaders, 'Referer')
|
||||
) {
|
||||
details.requestHeaders['Referer'] = `${details.initiatorOrigin}/`;
|
||||
}
|
||||
})()
|
||||
.catch(err => {
|
||||
cancel = managedAuthRequest;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
beforeSendListener: null as
|
||||
| ((
|
||||
details: {
|
||||
url: string;
|
||||
initiatorOrigin?: string;
|
||||
requestHeaders: Record<string, string>;
|
||||
},
|
||||
callback: (response: {
|
||||
cancel?: boolean;
|
||||
requestHeaders?: Record<string, string>;
|
||||
}) => void
|
||||
) => void)
|
||||
| null,
|
||||
}));
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: () => '/test-electron-path',
|
||||
},
|
||||
net: {
|
||||
fetch: vi.fn(),
|
||||
},
|
||||
protocol: {
|
||||
handle: vi.fn(),
|
||||
},
|
||||
session: {
|
||||
defaultSession: {
|
||||
webRequest: {
|
||||
onHeadersReceived: vi.fn(),
|
||||
onBeforeSendHeaders: vi.fn(listener => {
|
||||
state.beforeSendListener = listener;
|
||||
}),
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../src/main/auth/auth-session', () => ({
|
||||
executeAuthSessionRequest: vi.fn(),
|
||||
getAccessTokenForUrl: vi.fn(async () => null),
|
||||
initializeAuthSessions: vi.fn(async () => {}),
|
||||
isManagedAuthEndpoint: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
vi.mock('../../src/main/config', () => ({
|
||||
buildType: 'canary',
|
||||
isDev: false,
|
||||
}));
|
||||
|
||||
vi.mock('../../src/main/logger', () => ({
|
||||
logger: { error: vi.fn() },
|
||||
}));
|
||||
|
||||
import { registerProtocol } from '../../src/main/protocol';
|
||||
|
||||
async function runBeforeSendHeaders(details: {
|
||||
url: string;
|
||||
initiatorOrigin?: string;
|
||||
requestHeaders: Record<string, string>;
|
||||
}) {
|
||||
return await new Promise<{
|
||||
cancel?: boolean;
|
||||
requestHeaders?: Record<string, string>;
|
||||
}>(resolve => {
|
||||
state.beforeSendListener!(details, resolve);
|
||||
});
|
||||
}
|
||||
|
||||
describe('Electron protocol worker headers', () => {
|
||||
beforeEach(async () => {
|
||||
state.beforeSendListener = null;
|
||||
await registerProtocol();
|
||||
});
|
||||
|
||||
test.each([
|
||||
[
|
||||
'adds Referer for main window image-proxy request without Origin or Referer',
|
||||
{
|
||||
url: 'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
initiatorOrigin: 'assets://.',
|
||||
requestHeaders: {},
|
||||
},
|
||||
'assets://./',
|
||||
],
|
||||
[
|
||||
'adds Referer for popup window image-proxy request without Origin or Referer',
|
||||
{
|
||||
url: 'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
initiatorOrigin: 'assets://another-host',
|
||||
requestHeaders: {},
|
||||
},
|
||||
'assets://another-host/',
|
||||
],
|
||||
[
|
||||
'preserves existing Origin header without injecting Referer',
|
||||
{
|
||||
url: 'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
initiatorOrigin: 'assets://.',
|
||||
requestHeaders: { Origin: 'assets://.' },
|
||||
},
|
||||
undefined,
|
||||
],
|
||||
[
|
||||
'does not inject Referer for untrusted initiator',
|
||||
{
|
||||
url: 'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fa.png',
|
||||
initiatorOrigin: 'https://untrusted.example',
|
||||
requestHeaders: {},
|
||||
},
|
||||
undefined,
|
||||
],
|
||||
[
|
||||
'does not inject Referer for non-worker URLs',
|
||||
{
|
||||
url: 'https://external.example/image.png',
|
||||
initiatorOrigin: 'assets://.',
|
||||
requestHeaders: {},
|
||||
},
|
||||
undefined,
|
||||
],
|
||||
])('%s', async (_name, details, expectedReferer) => {
|
||||
const result = await runBeforeSendHeaders({
|
||||
...details,
|
||||
requestHeaders: { ...details.requestHeaders },
|
||||
});
|
||||
|
||||
expect(result.cancel).toBe(false);
|
||||
expect(result.requestHeaders?.Referer).toBe(expectedReferer);
|
||||
});
|
||||
});
|
||||
+15
-3
@@ -1,8 +1,9 @@
|
||||
import type { FeatureFlagService } from '@affine/core/modules/feature-flag';
|
||||
import type { PeekViewService } from '@affine/core/modules/peek-view';
|
||||
import { I18n } from '@affine/i18n';
|
||||
import { WithDisposable } from '@blocksuite/affine/global/lit';
|
||||
import { SignalWatcher, WithDisposable } from '@blocksuite/affine/global/lit';
|
||||
import type { ColorScheme } from '@blocksuite/affine/model';
|
||||
import { ImageProxyService } from '@blocksuite/affine/shared/adapters';
|
||||
import {
|
||||
type BlockStdScope,
|
||||
type EditorHost,
|
||||
@@ -152,8 +153,8 @@ function groupStreamObjects(answer: StreamObject[]): StreamGroup[] {
|
||||
return groups;
|
||||
}
|
||||
|
||||
export class ChatContentStreamObjects extends WithDisposable(
|
||||
ShadowlessElement
|
||||
export class ChatContentStreamObjects extends SignalWatcher(
|
||||
WithDisposable(ShadowlessElement)
|
||||
) {
|
||||
static override styles = css`
|
||||
.reasoning-wrapper {
|
||||
@@ -297,6 +298,13 @@ export class ChatContentStreamObjects extends WithDisposable(
|
||||
@state()
|
||||
private accessor toolGroupOverrides = new Map<string, boolean>();
|
||||
|
||||
private get imageProxyURL() {
|
||||
return (
|
||||
(this.std ?? this.host?.std)?.getOptional(ImageProxyService)
|
||||
?.imageProxyURL ?? BUILD_CONFIG.imageProxyUrl
|
||||
);
|
||||
}
|
||||
|
||||
private renderFrontendRead(streamObject: StreamObject) {
|
||||
if (
|
||||
(streamObject.type !== 'tool-call' &&
|
||||
@@ -442,6 +450,7 @@ export class ChatContentStreamObjects extends WithDisposable(
|
||||
<web-crawl-tool
|
||||
.data=${streamObject}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL}
|
||||
></web-crawl-tool>
|
||||
`;
|
||||
case 'web_search_exa':
|
||||
@@ -449,6 +458,7 @@ export class ChatContentStreamObjects extends WithDisposable(
|
||||
<web-search-tool
|
||||
.data=${streamObject}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL}
|
||||
></web-search-tool>
|
||||
`;
|
||||
case 'doc_compose':
|
||||
@@ -544,6 +554,7 @@ export class ChatContentStreamObjects extends WithDisposable(
|
||||
<web-crawl-tool
|
||||
.data=${streamObject}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL}
|
||||
></web-crawl-tool>
|
||||
`;
|
||||
case 'web_search_exa':
|
||||
@@ -551,6 +562,7 @@ export class ChatContentStreamObjects extends WithDisposable(
|
||||
<web-search-tool
|
||||
.data=${streamObject}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL}
|
||||
></web-search-tool>
|
||||
`;
|
||||
case 'doc_compose':
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* @vitest-environment happy-dom
|
||||
*/
|
||||
import { ImageProxyService } from '@blocksuite/affine/shared/adapters';
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { ChatContentStreamObjects } from '../../ai-message-content/stream-objects';
|
||||
import { ToolResultCard } from '../tool-result-card';
|
||||
import { WebCrawlTool } from '../web-crawl';
|
||||
import { WebSearchTool } from '../web-search';
|
||||
|
||||
function defineOnce(name: string, ctor: CustomElementConstructor) {
|
||||
if (!customElements.get(name)) {
|
||||
customElements.define(name, ctor);
|
||||
}
|
||||
}
|
||||
|
||||
describe('AI tool result image proxy', () => {
|
||||
beforeEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('uses the editor ImageProxyService URL and anonymous CORS on web tool favicons', async () => {
|
||||
defineOnce('tool-result-card', ToolResultCard);
|
||||
defineOnce('web-search-tool', WebSearchTool);
|
||||
defineOnce('web-crawl-tool', WebCrawlTool);
|
||||
defineOnce('chat-content-stream-objects', ChatContentStreamObjects);
|
||||
|
||||
const imageProxyService = new ImageProxyService({} as never);
|
||||
imageProxyService.setImageProxyURL(
|
||||
'https://selfhosted.example/api/worker/image-proxy'
|
||||
);
|
||||
|
||||
const stream = document.createElement(
|
||||
'chat-content-stream-objects'
|
||||
) as ChatContentStreamObjects;
|
||||
stream.host = {
|
||||
std: {
|
||||
getOptional: (token: unknown) =>
|
||||
token === ImageProxyService ? imageProxyService : undefined,
|
||||
},
|
||||
} as never;
|
||||
stream.answer = [
|
||||
{
|
||||
type: 'tool-result',
|
||||
toolCallId: 'call_search_1',
|
||||
toolName: 'web_search_exa',
|
||||
args: { query: 'affine' },
|
||||
result: [
|
||||
{
|
||||
title: 'Example',
|
||||
url: 'https://example.com',
|
||||
content: 'Snippet',
|
||||
favicon: 'https://example.com/favicon.png',
|
||||
publishedDate: '2026-01-01',
|
||||
author: 'Author',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'tool-result',
|
||||
toolCallId: 'call_crawl_1',
|
||||
toolName: 'web_crawl_exa',
|
||||
args: { url: 'https://example.com' },
|
||||
result: [
|
||||
{
|
||||
title: 'Example Page',
|
||||
url: 'https://example.com',
|
||||
content: 'Body',
|
||||
favicon: 'https://example.com/crawl-icon.png',
|
||||
publishedDate: '2026-01-01',
|
||||
author: 'Author',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
document.body.append(stream);
|
||||
await stream.updateComplete;
|
||||
const webSearch = stream.querySelector<WebSearchTool>('web-search-tool');
|
||||
const webCrawl = stream.querySelector<WebCrawlTool>('web-crawl-tool');
|
||||
expect(webSearch).toBeTruthy();
|
||||
expect(webCrawl).toBeTruthy();
|
||||
await webSearch!.updateComplete;
|
||||
await webCrawl!.updateComplete;
|
||||
|
||||
const searchCard =
|
||||
webSearch!.querySelector<ToolResultCard>('tool-result-card');
|
||||
const crawlCard =
|
||||
webCrawl!.querySelector<ToolResultCard>('tool-result-card');
|
||||
expect(searchCard).toBeTruthy();
|
||||
expect(crawlCard).toBeTruthy();
|
||||
await Promise.all([searchCard!.updateComplete, crawlCard!.updateComplete]);
|
||||
|
||||
const searchImgs = [...searchCard!.querySelectorAll('img')];
|
||||
const crawlImgs = [...crawlCard!.querySelectorAll('img')];
|
||||
expect(searchImgs.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawlImgs.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
for (const img of searchImgs) {
|
||||
expect(img.getAttribute('src')).toBe(
|
||||
'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Ffavicon.png'
|
||||
);
|
||||
expect(img.getAttribute('crossorigin')).toBe('anonymous');
|
||||
}
|
||||
for (const img of crawlImgs) {
|
||||
expect(img.getAttribute('src')).toBe(
|
||||
'https://selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fcrawl-icon.png'
|
||||
);
|
||||
expect(img.getAttribute('crossorigin')).toBe('anonymous');
|
||||
}
|
||||
|
||||
const searchImg = searchImgs[0];
|
||||
const searchFallback = searchImg.nextElementSibling as HTMLDivElement;
|
||||
searchImg.dispatchEvent(new Event('error'));
|
||||
expect(searchImg.style.display).toBe('none');
|
||||
expect(searchFallback.style.display).toBe('block');
|
||||
|
||||
imageProxyService.setImageProxyURL(
|
||||
'https://updated-selfhosted.example/api/worker/image-proxy'
|
||||
);
|
||||
await stream.updateComplete;
|
||||
await Promise.all([webSearch!.updateComplete, webCrawl!.updateComplete]);
|
||||
await Promise.all([searchCard!.updateComplete, crawlCard!.updateComplete]);
|
||||
|
||||
expect(searchImg.getAttribute('src')).toBe(
|
||||
'https://updated-selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Ffavicon.png'
|
||||
);
|
||||
expect(crawlImgs[0].getAttribute('src')).toBe(
|
||||
'https://updated-selfhosted.example/api/worker/image-proxy?url=https%3A%2F%2Fexample.com%2Fcrawl-icon.png'
|
||||
);
|
||||
|
||||
searchImg.dispatchEvent(new Event('load'));
|
||||
expect(searchImg.style.display).toBe('');
|
||||
expect(searchFallback.style.display).toBe('none');
|
||||
|
||||
stream.remove();
|
||||
});
|
||||
});
|
||||
@@ -249,11 +249,12 @@ export class ToolResultCard extends SignalWatcher(
|
||||
@property({ attribute: false })
|
||||
accessor width: Signal<number | undefined> | undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor imageProxyURL: string = BUILD_CONFIG.imageProxyUrl;
|
||||
|
||||
@state()
|
||||
private accessor isCollapsed = true;
|
||||
|
||||
private readonly imageProxyURL = BUILD_CONFIG.imageProxyUrl;
|
||||
|
||||
protected override render() {
|
||||
return html`
|
||||
<div class="ai-tool-result-wrapper">
|
||||
@@ -344,11 +345,22 @@ export class ToolResultCard extends SignalWatcher(
|
||||
return html`<div class="image-icon">
|
||||
<img
|
||||
src=${this.buildUrl(icon)}
|
||||
crossorigin="anonymous"
|
||||
@load=${(e: Event) => {
|
||||
const img = e.target as HTMLImageElement;
|
||||
img.style.display = '';
|
||||
const iconElement = img.nextElementSibling as HTMLDivElement | null;
|
||||
if (iconElement) {
|
||||
iconElement.style.display = 'none';
|
||||
}
|
||||
}}
|
||||
@error=${(e: Event) => {
|
||||
const img = e.target as HTMLImageElement;
|
||||
img.style.display = 'none';
|
||||
const iconElement = img.nextElementSibling as HTMLDivElement;
|
||||
iconElement.style.display = 'block';
|
||||
const iconElement = img.nextElementSibling as HTMLDivElement | null;
|
||||
if (iconElement) {
|
||||
iconElement.style.display = 'block';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div style="display: none;">${this.icon}</div>
|
||||
|
||||
@@ -39,6 +39,9 @@ export class WebCrawlTool extends WithDisposable(ShadowlessElement) {
|
||||
@property({ attribute: false })
|
||||
accessor width: Signal<number | undefined> | undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor imageProxyURL: string | undefined;
|
||||
|
||||
renderToolCall() {
|
||||
return html`
|
||||
<tool-call-card
|
||||
@@ -69,6 +72,7 @@ export class WebCrawlTool extends WithDisposable(ShadowlessElement) {
|
||||
},
|
||||
]}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL ?? BUILD_CONFIG.imageProxyUrl}
|
||||
></tool-result-card>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -39,6 +39,9 @@ export class WebSearchTool extends WithDisposable(ShadowlessElement) {
|
||||
@property({ attribute: false })
|
||||
accessor width: Signal<number | undefined> | undefined;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor imageProxyURL: string | undefined;
|
||||
|
||||
renderToolCall() {
|
||||
return html`
|
||||
<tool-call-card
|
||||
@@ -73,6 +76,7 @@ export class WebSearchTool extends WithDisposable(ShadowlessElement) {
|
||||
.footerIcons=${footerIcons}
|
||||
.results=${results}
|
||||
.width=${this.width}
|
||||
.imageProxyURL=${this.imageProxyURL ?? BUILD_CONFIG.imageProxyUrl}
|
||||
></tool-result-card>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { ColorScheme } from '@blocksuite/affine/model';
|
||||
import {
|
||||
codeBlockWrapMiddleware,
|
||||
defaultImageProxyMiddleware,
|
||||
ImageProxyService,
|
||||
} from '@blocksuite/affine/shared/adapters';
|
||||
import { unsafeCSSVarV2 } from '@blocksuite/affine/shared/theme';
|
||||
import {
|
||||
@@ -284,10 +283,6 @@ export class TextRenderer extends SignalWatcher(
|
||||
this.requestUpdate();
|
||||
if (this.state !== 'generating') {
|
||||
this._doc.load();
|
||||
const imageProxyService = this._host.std.get(ImageProxyService);
|
||||
imageProxyService.setImageProxyURL(
|
||||
imageProxyService.imageProxyURL
|
||||
);
|
||||
this._clearTimer();
|
||||
}
|
||||
})
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @vitest-environment happy-dom
|
||||
*/
|
||||
import 'fake-indexeddb/auto';
|
||||
|
||||
import { getStoreManager } from '@affine/core/blocksuite/manager/store';
|
||||
import { ServerService } from '@affine/core/modules/cloud/services/server';
|
||||
import {
|
||||
ExportManager,
|
||||
ExportManagerExtension,
|
||||
} from '@blocksuite/affine/blocks/surface';
|
||||
import { ViewExtensionManager } from '@blocksuite/affine/ext-loader';
|
||||
import { ImageProxyService } from '@blocksuite/affine/shared/adapters';
|
||||
import {
|
||||
LinkPreviewCache,
|
||||
LinkPreviewService,
|
||||
LinkPreviewServiceIdentifier,
|
||||
} from '@blocksuite/affine/shared/services';
|
||||
import { BlockStdScope } from '@blocksuite/affine/std';
|
||||
import { TestWorkspace } from '@blocksuite/affine/store/test';
|
||||
import { Framework } from '@toeverything/infra';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { AffineLinkPreviewExtension } from '../index';
|
||||
import { resolveImageProxyEndpoint } from '../link-preview-service';
|
||||
|
||||
function createSelfHostedFramework(baseUrl: string) {
|
||||
const framework = new Framework();
|
||||
framework.service(ServerService, {
|
||||
server: {
|
||||
baseUrl,
|
||||
},
|
||||
} as unknown as ServerService);
|
||||
return framework.provider();
|
||||
}
|
||||
|
||||
describe('AffineLinkPreviewExtension', () => {
|
||||
test('configures link preview, image proxy, clipboard middleware, and export manager before render', () => {
|
||||
const framework = createSelfHostedFramework('https://selfhosted.example');
|
||||
const viewManager = new ViewExtensionManager([AffineLinkPreviewExtension]);
|
||||
viewManager.configure(AffineLinkPreviewExtension, { framework });
|
||||
|
||||
const collection = new TestWorkspace({ id: 'test-workspace' });
|
||||
collection.meta.initialize();
|
||||
const store = collection.createDoc('test-doc').getStore({
|
||||
extensions: getStoreManager().config.init().value.get('store'),
|
||||
});
|
||||
|
||||
const std = new BlockStdScope({
|
||||
store,
|
||||
extensions: [
|
||||
LinkPreviewCache,
|
||||
LinkPreviewService,
|
||||
ExportManagerExtension,
|
||||
...viewManager.get('page'),
|
||||
],
|
||||
});
|
||||
|
||||
expect(std.get(LinkPreviewServiceIdentifier).endpoint).toBe(
|
||||
'https://selfhosted.example/api/worker/link-preview'
|
||||
);
|
||||
expect(store.get(ImageProxyService).imageProxyURL).toBe(
|
||||
'https://selfhosted.example/api/worker/image-proxy'
|
||||
);
|
||||
|
||||
expect(std.clipboard.configs.get('imageProxy')).toBe(
|
||||
'https://selfhosted.example/api/worker/image-proxy'
|
||||
);
|
||||
|
||||
const exportManager = new ExportManager(std);
|
||||
expect(
|
||||
(
|
||||
exportManager as unknown as {
|
||||
_imageProxyEndpoint?: string;
|
||||
_exportOptions: { imageProxyEndpoint: string };
|
||||
}
|
||||
)._imageProxyEndpoint ??
|
||||
(
|
||||
exportManager as unknown as {
|
||||
_exportOptions: { imageProxyEndpoint: string };
|
||||
}
|
||||
)._exportOptions.imageProxyEndpoint
|
||||
).toBe('https://selfhosted.example/api/worker/image-proxy');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['', null],
|
||||
[' ', null],
|
||||
['/', null],
|
||||
[
|
||||
'/api/worker/image-proxy',
|
||||
'https://selfhosted.example/api/worker/image-proxy',
|
||||
],
|
||||
[
|
||||
'https://proxy.example/api/worker/image-proxy',
|
||||
'https://proxy.example/api/worker/image-proxy',
|
||||
],
|
||||
])('validates configured image proxy endpoint %j', (value, expected) => {
|
||||
expect(resolveImageProxyEndpoint(value, 'https://selfhosted.example')).toBe(
|
||||
expected
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,10 @@ import {
|
||||
import { FrameworkProvider } from '@toeverything/infra';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { patchLinkPreviewService } from './link-preview-service';
|
||||
import {
|
||||
patchImageProxyService,
|
||||
patchLinkPreviewService,
|
||||
} from './link-preview-service';
|
||||
|
||||
const optionsSchema = z.object({
|
||||
framework: z.instanceof(FrameworkProvider).optional(),
|
||||
@@ -27,6 +30,9 @@ export class AffineLinkPreviewExtension extends ViewExtensionProvider<AffineLink
|
||||
return;
|
||||
}
|
||||
const { framework } = options;
|
||||
context.register(patchLinkPreviewService(framework));
|
||||
context.register([
|
||||
patchLinkPreviewService(framework),
|
||||
patchImageProxyService(framework),
|
||||
]);
|
||||
}
|
||||
}
|
||||
+36
@@ -1,9 +1,14 @@
|
||||
import {
|
||||
customImageProxyMiddleware,
|
||||
ImageProxyService,
|
||||
} from '@blocksuite/affine/shared/adapters';
|
||||
import {
|
||||
LinkPreviewCacheIdentifier,
|
||||
type LinkPreviewCacheProvider,
|
||||
LinkPreviewService,
|
||||
LinkPreviewServiceIdentifier,
|
||||
} from '@blocksuite/affine/shared/services';
|
||||
import { LifeCycleWatcher } from '@blocksuite/affine/std';
|
||||
import { type ExtensionType } from '@blocksuite/affine/store';
|
||||
import type { Container } from '@blocksuite/global/di';
|
||||
import type { FrameworkProvider } from '@toeverything/infra';
|
||||
@@ -11,6 +16,7 @@ import type { FrameworkProvider } from '@toeverything/infra';
|
||||
import { ServerService } from '../../../modules/cloud/services/server';
|
||||
|
||||
const LINK_PREVIEW_PATH = '/api/worker/link-preview';
|
||||
const IMAGE_PROXY_PATH = '/api/worker/image-proxy';
|
||||
|
||||
export function resolveLinkPreviewEndpoint(value: string, baseUrl: string) {
|
||||
if (!value.trim() || !URL.canParse(value, baseUrl)) return null;
|
||||
@@ -18,6 +24,12 @@ export function resolveLinkPreviewEndpoint(value: string, baseUrl: string) {
|
||||
return endpoint.pathname === LINK_PREVIEW_PATH ? endpoint.toString() : null;
|
||||
}
|
||||
|
||||
export function resolveImageProxyEndpoint(value: string, baseUrl: string) {
|
||||
if (!value.trim() || !URL.canParse(value, baseUrl)) return null;
|
||||
const endpoint = new URL(value, baseUrl);
|
||||
return endpoint.pathname === IMAGE_PROXY_PATH ? endpoint.toString() : null;
|
||||
}
|
||||
|
||||
class AffineLinkPreviewService extends LinkPreviewService {
|
||||
constructor(endpoint: string | null, cache: LinkPreviewCacheProvider) {
|
||||
super(cache, createAffineLinkPreviewFetch(BUILD_CONFIG.appVersion));
|
||||
@@ -61,3 +73,27 @@ export function patchLinkPreviewService(
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function patchImageProxyService(
|
||||
framework: FrameworkProvider
|
||||
): ExtensionType {
|
||||
const server = framework.get(ServerService).server;
|
||||
const imageProxyUrl = resolveImageProxyEndpoint(
|
||||
BUILD_CONFIG.imageProxyUrl,
|
||||
server.baseUrl
|
||||
);
|
||||
|
||||
class AffineImageProxyLifeCycleWatcher extends LifeCycleWatcher {
|
||||
static override key = 'affine-image-proxy';
|
||||
|
||||
override created() {
|
||||
if (!imageProxyUrl) return;
|
||||
this.std.store
|
||||
.getOptional(ImageProxyService)
|
||||
?.setImageProxyURL(imageProxyUrl);
|
||||
this.std.clipboard.use(customImageProxyMiddleware(imageProxyUrl));
|
||||
}
|
||||
}
|
||||
|
||||
return AffineImageProxyLifeCycleWatcher;
|
||||
}
|
||||
@@ -47,7 +47,11 @@ import { RefNodeSlotsProvider } from '@blocksuite/affine/inlines/reference';
|
||||
import { BlockStdScope } from '@blocksuite/affine/std';
|
||||
import type { Workspace } from '@blocksuite/affine/store';
|
||||
import { type Signal, signal } from '@preact/signals-core';
|
||||
import { useFramework, useService } from '@toeverything/infra';
|
||||
import {
|
||||
type FrameworkProvider,
|
||||
useFramework,
|
||||
useService,
|
||||
} from '@toeverything/infra';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
@@ -77,14 +81,19 @@ function useAIRequestService() {
|
||||
);
|
||||
}
|
||||
|
||||
function createMockStd(workspace: Workspace) {
|
||||
function createMockStd(workspace: Workspace, framework: FrameworkProvider) {
|
||||
workspace.meta.initialize();
|
||||
// just pick a random doc for now
|
||||
const store = workspace.docs.values().next().value?.getStore();
|
||||
if (!store) return null;
|
||||
const std = new BlockStdScope({
|
||||
store,
|
||||
extensions: [...getViewManager().config.init().value.get('page')],
|
||||
extensions: [
|
||||
...getViewManager()
|
||||
.config.init()
|
||||
.linkPreview(framework)
|
||||
.value.get('page'),
|
||||
],
|
||||
});
|
||||
std.render();
|
||||
return std;
|
||||
@@ -92,10 +101,11 @@ function createMockStd(workspace: Workspace) {
|
||||
|
||||
function useMockStd() {
|
||||
const workspace = useService(WorkspaceService).workspace;
|
||||
const framework = useFramework();
|
||||
const std = useMemo(() => {
|
||||
if (!workspace) return null;
|
||||
return createMockStd(workspace.docCollection);
|
||||
}, [workspace]);
|
||||
return createMockStd(workspace.docCollection, framework);
|
||||
}, [framework, workspace]);
|
||||
return std;
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -154,7 +154,12 @@ export const LinkPreview = ({
|
||||
return (
|
||||
<section className={styles.linkPreview} aria-label="Link preview">
|
||||
{preview.images?.[0] ? (
|
||||
<img className={styles.previewMedia} src={preview.images[0]} alt="" />
|
||||
<img
|
||||
className={styles.previewMedia}
|
||||
src={preview.images[0]}
|
||||
alt=""
|
||||
crossOrigin="anonymous"
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.previewMediaPlaceholder} aria-hidden="true">
|
||||
<LinkIcon />
|
||||
@@ -168,6 +173,7 @@ export const LinkPreview = ({
|
||||
className={styles.previewFavicon}
|
||||
src={preview.favicons[0]}
|
||||
alt=""
|
||||
crossOrigin="anonymous"
|
||||
/>
|
||||
) : null}
|
||||
{preview.siteName || hostname}
|
||||
|
||||
+9
-1
@@ -663,6 +663,7 @@ describe('share preview presentation', () => {
|
||||
url: shared.content.url!,
|
||||
title: 'Provider title',
|
||||
images: ['https://youtube.com/thumbnail.jpg'],
|
||||
favicons: ['https://youtube.com/favicon.ico'],
|
||||
durationSeconds: 90,
|
||||
transcript: {
|
||||
segments: [{ text: ' Hello\n\tworld ' }, { text: ' again ' }],
|
||||
@@ -683,9 +684,16 @@ describe('share preview presentation', () => {
|
||||
expect(screen.getByText('Hello world again')).toBeTruthy();
|
||||
expect(screen.getByText('1:30')).toBeTruthy();
|
||||
expect(screen.getByText('Selected passage')).toBeTruthy();
|
||||
expect(container.querySelector('section > img')?.getAttribute('src')).toBe(
|
||||
const previewImg = container.querySelector('section > img');
|
||||
expect(previewImg?.getAttribute('src')).toBe(
|
||||
'https://youtube.com/thumbnail.jpg'
|
||||
);
|
||||
expect(previewImg?.getAttribute('crossorigin')).toBe('anonymous');
|
||||
const imgs = [...container.querySelectorAll('img')];
|
||||
expect(imgs).toHaveLength(2);
|
||||
for (const img of imgs) {
|
||||
expect(img.getAttribute('crossorigin')).toBe('anonymous');
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
|
||||
@@ -9,7 +9,6 @@ import { PageDetailEditor } from '@affine/core/components/page-detail-editor';
|
||||
import { DetailPageWrapper } from '@affine/core/desktop/pages/workspace/detail-page/detail-page-wrapper';
|
||||
import { PageHeader } from '@affine/core/mobile/components';
|
||||
import { AIButtonService } from '@affine/core/modules/ai-button';
|
||||
import { ServerService } from '@affine/core/modules/cloud';
|
||||
import { DocService } from '@affine/core/modules/doc';
|
||||
import { DocDisplayMetaService } from '@affine/core/modules/doc-display-meta';
|
||||
import { EditorService } from '@affine/core/modules/editor';
|
||||
@@ -23,10 +22,6 @@ import { i18nTime, useI18n } from '@affine/i18n';
|
||||
import { track } from '@affine/track';
|
||||
import { DisposableGroup } from '@blocksuite/affine/global/disposable';
|
||||
import { RefNodeSlotsProvider } from '@blocksuite/affine/inlines/reference';
|
||||
import {
|
||||
customImageProxyMiddleware,
|
||||
ImageProxyService,
|
||||
} from '@blocksuite/affine/shared/adapters';
|
||||
import { EditIcon, ViewIcon as ViewIconBlocksuite } from '@blocksuite/icons/rc';
|
||||
import {
|
||||
FrameworkScope,
|
||||
@@ -154,23 +149,8 @@ const DetailPageImpl = ({
|
||||
};
|
||||
}, [globalContext, isInTrash]);
|
||||
|
||||
const server = useService(ServerService).server;
|
||||
|
||||
const onLoad = useCallback(
|
||||
(editorContainer: AffineEditorContainer) => {
|
||||
// provide image proxy endpoint to blocksuite
|
||||
const imageProxyUrl = new URL(
|
||||
BUILD_CONFIG.imageProxyUrl,
|
||||
server.baseUrl
|
||||
).toString();
|
||||
|
||||
editorContainer.std.clipboard.use(
|
||||
customImageProxyMiddleware(imageProxyUrl)
|
||||
);
|
||||
editorContainer.doc
|
||||
.get(ImageProxyService)
|
||||
.setImageProxyURL(imageProxyUrl);
|
||||
|
||||
// provide page mode and updated date to blocksuite
|
||||
const refNodeService =
|
||||
editorContainer.std.getOptional(RefNodeSlotsProvider);
|
||||
@@ -204,7 +184,7 @@ const DetailPageImpl = ({
|
||||
disposable.dispose();
|
||||
};
|
||||
},
|
||||
[docCollection.id, editor, jumpToPageBlock, openPage, server]
|
||||
[docCollection.id, editor, jumpToPageBlock, openPage]
|
||||
);
|
||||
|
||||
const immersiveZoomToolbarBottom = getImmersiveZoomToolbarBottom({
|
||||
|
||||
Reference in new issue
Block a user