Some checks failed
Build & Test / Analyze (javascript, affine) (push) Failing after 4s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 4s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 3s
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 4s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 3s
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Release / Canary Gate (push) Has been skipped
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Copilot Test Automatically / Setup Test (push) Failing after 1s
Release / Prepare (push) Failing after 2s
Release / Release Cloud (push) Has been skipped
Release / Release Desktop (push) Has been skipped
Release / Release Docker Image (push) Has been skipped
Release / Release Mobile (push) Has been skipped
296 lines
8.6 KiB
TypeScript
296 lines
8.6 KiB
TypeScript
import path, { join } from 'node:path';
|
|
import { pathToFileURL } from 'node:url';
|
|
|
|
import { app, net, protocol, session } from 'electron';
|
|
|
|
import { anotherHost, mainHost } from '../shared/internal-origin';
|
|
import {
|
|
isPathInsideBase,
|
|
isWindows,
|
|
resolveExistingPathInBase,
|
|
resolvePathInBase,
|
|
resourcesPath,
|
|
} from '../shared/utils';
|
|
import {
|
|
executeAuthSessionRequest,
|
|
getAccessTokenForUrl,
|
|
initializeAuthSessions,
|
|
isManagedAuthEndpoint,
|
|
} from './auth/auth-session';
|
|
import { buildType, isDev } from './config';
|
|
import { logger } from './logger';
|
|
|
|
const webStaticDir = join(resourcesPath, 'web-static');
|
|
const devServerBase = process.env.DEV_SERVER_URL;
|
|
const localWhiteListDirs = [
|
|
path.resolve(app.getPath('sessionData')),
|
|
path.resolve(app.getPath('temp')),
|
|
];
|
|
|
|
function isPathInWhiteList(filepath: string) {
|
|
return localWhiteListDirs.some(whitelistDir =>
|
|
isPathInsideBase(whitelistDir, filepath, {
|
|
caseInsensitive: isWindows(),
|
|
})
|
|
);
|
|
}
|
|
|
|
async function resolveWhitelistedLocalPath(filepath: string) {
|
|
for (const whitelistDir of localWhiteListDirs) {
|
|
try {
|
|
return await resolveExistingPathInBase(whitelistDir, filepath, {
|
|
caseInsensitive: isWindows(),
|
|
label: 'filepath',
|
|
});
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
throw new Error('Invalid filepath');
|
|
}
|
|
|
|
const apiBaseByBuildType: Record<typeof buildType, string> = {
|
|
stable: 'https://app.affine.pro',
|
|
beta: 'https://insider.affine.pro',
|
|
internal: 'https://insider.affine.pro',
|
|
canary: 'https://affine.fail',
|
|
};
|
|
|
|
function resolveApiBaseUrl() {
|
|
if (isDev && devServerBase) {
|
|
return devServerBase;
|
|
}
|
|
|
|
return apiBaseByBuildType[buildType] ?? apiBaseByBuildType.stable;
|
|
}
|
|
|
|
function buildTargetUrl(base: string, urlObject: URL) {
|
|
return new URL(`${urlObject.pathname}${urlObject.search}`, base).toString();
|
|
}
|
|
|
|
async function proxyRequest(
|
|
request: Request,
|
|
urlObject: URL,
|
|
base: string,
|
|
options: { bypassCustomProtocolHandlers?: boolean } = {}
|
|
) {
|
|
const { bypassCustomProtocolHandlers = true } = options;
|
|
const targetUrl = buildTargetUrl(base, urlObject);
|
|
return await executeAuthSessionRequest(request, targetUrl, request =>
|
|
net.fetch(
|
|
bypassCustomProtocolHandlers
|
|
? Object.assign(request, { bypassCustomProtocolHandlers: true })
|
|
: request
|
|
)
|
|
);
|
|
}
|
|
|
|
async function handleFileRequest(request: Request) {
|
|
const urlObject = new URL(request.url);
|
|
|
|
if (urlObject.host === anotherHost) {
|
|
urlObject.host = mainHost;
|
|
}
|
|
|
|
const isAbsolutePath = urlObject.host !== '.';
|
|
const isApiRequest =
|
|
!isAbsolutePath &&
|
|
(urlObject.pathname.startsWith('/api/') ||
|
|
urlObject.pathname === '/graphql');
|
|
|
|
if (isApiRequest) {
|
|
return proxyRequest(request, urlObject, resolveApiBaseUrl());
|
|
}
|
|
|
|
const isFontRequest =
|
|
urlObject.pathname &&
|
|
/\.(woff2?|ttf|otf)$/i.test(urlObject.pathname.split('?')[0] ?? '');
|
|
|
|
// Redirect to webpack dev server if available
|
|
if (isDev && devServerBase && !isAbsolutePath && !isFontRequest) {
|
|
return proxyRequest(request, urlObject, devServerBase, {
|
|
bypassCustomProtocolHandlers: false,
|
|
});
|
|
}
|
|
const clonedRequest = Object.assign(request.clone(), {
|
|
bypassCustomProtocolHandlers: true,
|
|
});
|
|
// this will be file types (in the web-static folder)
|
|
let filepath = '';
|
|
|
|
// for relative path, load the file in resources
|
|
if (!isAbsolutePath) {
|
|
if (urlObject.pathname.split('/').at(-1)?.includes('.')) {
|
|
const decodedPath = decodeURIComponent(urlObject.pathname).replace(
|
|
/^\/+/,
|
|
''
|
|
);
|
|
filepath = resolvePathInBase(webStaticDir, decodedPath, {
|
|
caseInsensitive: isWindows(),
|
|
label: 'filepath',
|
|
});
|
|
} else {
|
|
// else, fallback to load the index.html instead
|
|
filepath = join(webStaticDir, 'index.html');
|
|
}
|
|
} else {
|
|
filepath = decodeURIComponent(urlObject.pathname);
|
|
// on windows, the path could be start with '/'
|
|
if (isWindows()) {
|
|
filepath = path.resolve(filepath.replace(/^\//, ''));
|
|
}
|
|
if (urlObject.host !== 'local-file' || !isPathInWhiteList(filepath)) {
|
|
throw new Error('Invalid filepath');
|
|
}
|
|
filepath = await resolveWhitelistedLocalPath(filepath);
|
|
}
|
|
return net.fetch(pathToFileURL(filepath).toString(), clonedRequest);
|
|
}
|
|
|
|
const needRefererDomains = [
|
|
/^(?:[a-zA-Z0-9-]+\.)*youtube\.com$/,
|
|
/^(?:[a-zA-Z0-9-]+\.)*youtube-nocookie\.com$/,
|
|
/^(?:[a-zA-Z0-9-]+\.)*googlevideo\.com$/,
|
|
];
|
|
const defaultReferer = 'https://client.affine.local/';
|
|
const affineDomains = [
|
|
/^(?:[a-z0-9-]+\.)*usercontent\.affine\.pro$/i,
|
|
/^(?:[a-z0-9-]+\.)*affine\.pro$/i,
|
|
/^(?:[a-z0-9-]+\.)*affine\.fail$/i,
|
|
/^(?:[a-z0-9-]+\.)*affine\.run$/i,
|
|
];
|
|
|
|
function setHeader(
|
|
headers: Record<string, string[]>,
|
|
name: string,
|
|
value: string
|
|
) {
|
|
Object.keys(headers).forEach(key => {
|
|
if (key.toLowerCase() === name.toLowerCase()) {
|
|
delete headers[key];
|
|
}
|
|
});
|
|
headers[name] = [value];
|
|
}
|
|
|
|
function ensureFrameAncestors(
|
|
headers: Record<string, string[]>,
|
|
directive: string
|
|
) {
|
|
const cspHeaderKey = Object.keys(headers).find(
|
|
key => key.toLowerCase() === 'content-security-policy'
|
|
);
|
|
if (!cspHeaderKey) {
|
|
headers['Content-Security-Policy'] = [`frame-ancestors ${directive}`];
|
|
return;
|
|
}
|
|
|
|
const values = headers[cspHeaderKey];
|
|
headers[cspHeaderKey] = values.map(val => {
|
|
if (typeof val !== 'string') return val as any;
|
|
const directives = val
|
|
.split(';')
|
|
.map(v => v.trim())
|
|
.filter(Boolean)
|
|
.filter(d => !d.toLowerCase().startsWith('frame-ancestors'));
|
|
directives.push(`frame-ancestors ${directive}`);
|
|
return directives.join('; ');
|
|
});
|
|
}
|
|
|
|
function allowCors(
|
|
headers: Record<string, string[]>,
|
|
origin: string = 'assets://.'
|
|
) {
|
|
// Object-storage upload and Copilot URLs do not include application CORS headers.
|
|
setHeader(headers, 'Access-Control-Allow-Origin', origin);
|
|
setHeader(headers, 'Access-Control-Allow-Credentials', 'true');
|
|
setHeader(headers, 'Access-Control-Allow-Methods', 'GET, HEAD, PUT, OPTIONS');
|
|
setHeader(
|
|
headers,
|
|
'Access-Control-Allow-Headers',
|
|
'*, Authorization, Content-Type, Range'
|
|
);
|
|
}
|
|
|
|
export async function registerProtocol() {
|
|
await initializeAuthSessions();
|
|
|
|
protocol.handle('assets', request => {
|
|
return handleFileRequest(request);
|
|
});
|
|
|
|
session.defaultSession.webRequest.onHeadersReceived(
|
|
(responseDetails, callback) => {
|
|
const { responseHeaders, url } = responseDetails;
|
|
(async () => {
|
|
if (responseHeaders) {
|
|
const { protocol, hostname } = new URL(url);
|
|
|
|
// Adjust CORS for local assets and application-owned object storage.
|
|
if (protocol === 'assets:') {
|
|
delete responseHeaders['access-control-allow-origin'];
|
|
delete responseHeaders['access-control-allow-headers'];
|
|
delete responseHeaders['Access-Control-Allow-Origin'];
|
|
delete responseHeaders['Access-Control-Allow-Headers'];
|
|
setHeader(responseHeaders, 'X-Frame-Options', 'SAMEORIGIN');
|
|
ensureFrameAncestors(responseHeaders, "'self'");
|
|
} else if (
|
|
(protocol === 'http:' || protocol === 'https:') &&
|
|
affineDomains.some(regex => regex.test(hostname))
|
|
) {
|
|
allowCors(responseHeaders);
|
|
}
|
|
}
|
|
})()
|
|
.catch(err => {
|
|
logger.error('error handling headers received', err);
|
|
})
|
|
.finally(() => {
|
|
callback({ responseHeaders });
|
|
});
|
|
}
|
|
);
|
|
|
|
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
|
|
const url = new URL(details.url);
|
|
const managedAuthRequest =
|
|
(url.protocol === 'http:' ||
|
|
url.protocol === 'https:' ||
|
|
url.protocol === 'ws:' ||
|
|
url.protocol === 'wss:') &&
|
|
isManagedAuthEndpoint(details.url);
|
|
let cancel = false;
|
|
|
|
(async () => {
|
|
if (managedAuthRequest) {
|
|
delete details.requestHeaders.authorization;
|
|
delete details.requestHeaders.Authorization;
|
|
const token = await getAccessTokenForUrl(details.url, 120_000);
|
|
if (token) {
|
|
details.requestHeaders.Authorization = `Bearer ${token}`;
|
|
}
|
|
}
|
|
|
|
const hostname = url.hostname;
|
|
const needReferer = needRefererDomains.some(regex =>
|
|
regex.test(hostname)
|
|
);
|
|
if (needReferer && !details.requestHeaders['Referer']) {
|
|
details.requestHeaders['Referer'] = defaultReferer;
|
|
}
|
|
})()
|
|
.catch(err => {
|
|
cancel = managedAuthRequest;
|
|
logger.error('error handling before send headers', err);
|
|
})
|
|
.finally(() => {
|
|
callback({
|
|
cancel,
|
|
requestHeaders: details.requestHeaders,
|
|
});
|
|
});
|
|
});
|
|
}
|