mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-09-23 20:18:42 +08:00
chore: drop old client support (#14369)
This commit is contained in:
@@ -11,15 +11,40 @@
|
||||
* @param init Request initialization options
|
||||
* @returns Promise with the fetch Response
|
||||
*/
|
||||
const CSRF_COOKIE_NAME = 'affine_csrf_token';
|
||||
|
||||
function getCookieValue(name: string) {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cookies = document.cookie ? document.cookie.split('; ') : [];
|
||||
for (const cookie of cookies) {
|
||||
const idx = cookie.indexOf('=');
|
||||
const key = idx === -1 ? cookie : cookie.slice(0, idx);
|
||||
if (key === name) {
|
||||
return idx === -1 ? '' : cookie.slice(idx + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const affineFetch = (
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
): Promise<Response> => {
|
||||
const method = init?.method?.toUpperCase() ?? 'GET';
|
||||
const csrfToken =
|
||||
method !== 'GET' && method !== 'HEAD'
|
||||
? getCookieValue(CSRF_COOKIE_NAME)
|
||||
: null;
|
||||
|
||||
return fetch(input, {
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
'x-affine-version': BUILD_CONFIG.appVersion,
|
||||
...(csrfToken ? { 'x-affine-csrf-token': csrfToken } : {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -64,7 +64,7 @@ export function UserDropdown({ isCollapsed }: UserDropdownProps) {
|
||||
const relative = useRevalidateCurrentUser();
|
||||
|
||||
const handleLogout = useCallback(() => {
|
||||
affineFetch('/api/auth/sign-out')
|
||||
affineFetch('/api/auth/sign-out', { method: 'POST' })
|
||||
.then(() => {
|
||||
toast.success('Logged out successfully');
|
||||
return relative();
|
||||
|
||||
+6
-2
@@ -28,7 +28,9 @@ object AuthInitializer {
|
||||
.get(server.host + CookieStore.AFFINE_SESSION)
|
||||
val userIdCookieStr = AFFiNEApp.context().dataStore
|
||||
.get(server.host + CookieStore.AFFINE_USER_ID)
|
||||
if (sessionCookieStr.isEmpty() || userIdCookieStr.isEmpty()) {
|
||||
val csrfCookieStr = AFFiNEApp.context().dataStore
|
||||
.get(server.host + CookieStore.AFFINE_CSRF_TOKEN)
|
||||
if (sessionCookieStr.isEmpty() || userIdCookieStr.isEmpty() || csrfCookieStr.isEmpty()) {
|
||||
Timber.i("[init] user has not signed in yet.")
|
||||
return@launch
|
||||
}
|
||||
@@ -38,6 +40,8 @@ object AuthInitializer {
|
||||
?: error("Parse session cookie fail:[ cookie = $sessionCookieStr ]"),
|
||||
Cookie.parse(server, userIdCookieStr)
|
||||
?: error("Parse user id cookie fail:[ cookie = $userIdCookieStr ]"),
|
||||
Cookie.parse(server, csrfCookieStr)
|
||||
?: error("Parse csrf token cookie fail:[ cookie = $csrfCookieStr ]"),
|
||||
)
|
||||
CookieStore.saveCookies(server.host, cookies)
|
||||
FileTree.get()?.checkAndUploadOldLogs(server)
|
||||
@@ -49,4 +53,4 @@ object AuthInitializer {
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+7
-1
@@ -43,9 +43,15 @@ class AuthPlugin : Plugin() {
|
||||
launch(Dispatchers.IO) {
|
||||
try {
|
||||
val endpoint = call.getStringEnsure("endpoint")
|
||||
val csrfToken = CookieStore.getCookie(endpoint.toHttpUrl(), CookieStore.AFFINE_CSRF_TOKEN)
|
||||
val request = Request.Builder()
|
||||
.url("$endpoint/api/auth/sign-out")
|
||||
.get()
|
||||
.post("".toRequestBody("application/json".toMediaTypeOrNull()))
|
||||
.apply {
|
||||
if (csrfToken != null) {
|
||||
addHeader("x-affine-csrf-token", csrfToken)
|
||||
}
|
||||
}
|
||||
.build()
|
||||
OkHttp.client.newCall(request).executeAsync().use { response ->
|
||||
if (response.code >= 400) {
|
||||
|
||||
+5
-1
@@ -54,6 +54,7 @@ object CookieStore {
|
||||
|
||||
const val AFFINE_SESSION = "affine_session"
|
||||
const val AFFINE_USER_ID = "affine_user_id"
|
||||
const val AFFINE_CSRF_TOKEN = "affine_csrf_token"
|
||||
|
||||
private val _cookies = ConcurrentHashMap<String, List<Cookie>>()
|
||||
|
||||
@@ -68,6 +69,9 @@ object CookieStore {
|
||||
AFFiNEApp.context().dataStore.set(host + AFFINE_USER_ID, it.toString())
|
||||
Firebase.crashlytics.setUserId(it.value)
|
||||
}
|
||||
cookies.find { it.name == AFFINE_CSRF_TOKEN }?.let {
|
||||
AFFiNEApp.context().dataStore.set(host + AFFINE_CSRF_TOKEN, it.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,4 +81,4 @@ object CookieStore {
|
||||
.let { _cookies[it] }
|
||||
?.find { cookie -> cookie.name == name }
|
||||
?.value
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
"react": "^19.2.1",
|
||||
"react-dom": "^19.2.1",
|
||||
"react-router-dom": "^6.30.3",
|
||||
"uuid": "^11.1.0",
|
||||
"uuid": "^13.0.0",
|
||||
"webm-muxer": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
"semver": "^7.7.3",
|
||||
"tree-kill": "^1.2.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"uuid": "^11.1.0",
|
||||
"uuid": "^13.0.0",
|
||||
"vitest": "^3.2.4",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
|
||||
@@ -88,7 +88,9 @@ async function handleAffineUrl(url: string) {
|
||||
|
||||
if (
|
||||
!method ||
|
||||
(method !== 'magic-link' && method !== 'oauth') ||
|
||||
(method !== 'magic-link' &&
|
||||
method !== 'oauth' &&
|
||||
method !== 'open-app-signin') ||
|
||||
!payload
|
||||
) {
|
||||
logger.error('Invalid authentication url', url);
|
||||
|
||||
@@ -2,35 +2,7 @@ import { app } from 'electron';
|
||||
|
||||
import { anotherHost, mainHost } from './constants';
|
||||
import { openExternalSafely } from './security/open-external';
|
||||
|
||||
const extractRedirectTarget = (rawUrl: string) => {
|
||||
try {
|
||||
const parsed = new URL(rawUrl);
|
||||
const redirectUri = parsed.searchParams.get('redirect_uri');
|
||||
if (redirectUri) {
|
||||
return redirectUri;
|
||||
}
|
||||
|
||||
if (parsed.hash) {
|
||||
const hash = parsed.hash.startsWith('#')
|
||||
? parsed.hash.slice(1)
|
||||
: parsed.hash;
|
||||
|
||||
const queryIndex = hash.indexOf('?');
|
||||
if (queryIndex !== -1) {
|
||||
const hashParams = new URLSearchParams(hash.slice(queryIndex + 1));
|
||||
const hashRedirect = hashParams.get('redirect_uri');
|
||||
if (hashRedirect) {
|
||||
return hashRedirect;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
import { validateRedirectProxyUrl } from './security/redirect-proxy';
|
||||
|
||||
app.on('web-contents-created', (_, contents) => {
|
||||
const isInternalUrl = (url: string) => {
|
||||
@@ -80,17 +52,18 @@ app.on('web-contents-created', (_, contents) => {
|
||||
console.error('[security] Failed to open external URL:', error);
|
||||
});
|
||||
} else if (url.includes('/redirect-proxy')) {
|
||||
const redirectTarget = extractRedirectTarget(url);
|
||||
if (redirectTarget) {
|
||||
openExternalSafely(redirectTarget).catch(error => {
|
||||
console.error('[security] Failed to open external URL:', error);
|
||||
});
|
||||
} else {
|
||||
const result = validateRedirectProxyUrl(url);
|
||||
if (!result.allow) {
|
||||
console.warn(
|
||||
'[security] Blocked redirect proxy with missing redirect target:',
|
||||
url
|
||||
`[security] Blocked redirect proxy: ${result.reason}`,
|
||||
result.redirectTarget ?? url
|
||||
);
|
||||
return { action: 'deny' };
|
||||
}
|
||||
|
||||
openExternalSafely(result.redirectTarget).catch(error => {
|
||||
console.error('[security] Failed to open external URL:', error);
|
||||
});
|
||||
}
|
||||
// Prevent creating new window in application
|
||||
return { action: 'deny' };
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { isAllowedRedirectTarget } from '@toeverything/infra/utils';
|
||||
|
||||
import { buildType, isDev } from '../config';
|
||||
|
||||
const API_BASE_BY_BUILD_TYPE: Record<typeof buildType, string> = {
|
||||
stable: 'https://app.affine.pro',
|
||||
beta: 'https://insider.affine.pro',
|
||||
internal: 'https://insider.affine.pro',
|
||||
canary: 'https://affine.fail',
|
||||
};
|
||||
|
||||
function resolveCurrentHostnameForRedirectAllowlist() {
|
||||
const devServerBase = process.env.DEV_SERVER_URL;
|
||||
const base =
|
||||
isDev && devServerBase
|
||||
? devServerBase
|
||||
: (API_BASE_BY_BUILD_TYPE[buildType] ?? API_BASE_BY_BUILD_TYPE.stable);
|
||||
|
||||
try {
|
||||
return new URL(base).hostname;
|
||||
} catch {
|
||||
return 'app.affine.pro';
|
||||
}
|
||||
}
|
||||
|
||||
export function extractRedirectTarget(rawUrl: string) {
|
||||
try {
|
||||
const parsed = new URL(rawUrl);
|
||||
const redirectUri = parsed.searchParams.get('redirect_uri');
|
||||
if (redirectUri) {
|
||||
return redirectUri;
|
||||
}
|
||||
|
||||
if (parsed.hash) {
|
||||
const hash = parsed.hash.startsWith('#')
|
||||
? parsed.hash.slice(1)
|
||||
: parsed.hash;
|
||||
|
||||
const queryIndex = hash.indexOf('?');
|
||||
if (queryIndex !== -1) {
|
||||
const hashParams = new URLSearchParams(hash.slice(queryIndex + 1));
|
||||
const hashRedirect = hashParams.get('redirect_uri');
|
||||
if (hashRedirect) {
|
||||
return hashRedirect;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type RedirectProxyValidationResult =
|
||||
| {
|
||||
allow: true;
|
||||
redirectTarget: string;
|
||||
}
|
||||
| {
|
||||
allow: false;
|
||||
reason: 'missing_redirect_target' | 'untrusted_redirect_target';
|
||||
redirectTarget?: string;
|
||||
};
|
||||
|
||||
export function validateRedirectProxyUrl(
|
||||
rawUrl: string
|
||||
): RedirectProxyValidationResult {
|
||||
const redirectTarget = extractRedirectTarget(rawUrl);
|
||||
if (!redirectTarget) {
|
||||
return { allow: false, reason: 'missing_redirect_target' };
|
||||
}
|
||||
|
||||
const currentHostname = resolveCurrentHostnameForRedirectAllowlist();
|
||||
if (!isAllowedRedirectTarget(redirectTarget, { currentHostname })) {
|
||||
return {
|
||||
allow: false,
|
||||
reason: 'untrusted_redirect_target',
|
||||
redirectTarget,
|
||||
};
|
||||
}
|
||||
|
||||
return { allow: true, redirectTarget };
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import * as dns from 'node:dns/promises';
|
||||
import { BlockList, isIP } from 'node:net';
|
||||
|
||||
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
|
||||
const BLOCKED_IPS = new BlockList();
|
||||
const ALLOWED_IPV6 = new BlockList();
|
||||
|
||||
function stripZoneId(address: string) {
|
||||
const idx = address.indexOf('%');
|
||||
return idx === -1 ? address : address.slice(0, idx);
|
||||
}
|
||||
|
||||
// Use Node's built-in BlockList (Electron 39 ships with Node 22.x).
|
||||
for (const [network, prefix] of [
|
||||
['0.0.0.0', 8],
|
||||
['10.0.0.0', 8],
|
||||
['127.0.0.0', 8],
|
||||
['169.254.0.0', 16],
|
||||
['172.16.0.0', 12],
|
||||
['192.168.0.0', 16],
|
||||
['100.64.0.0', 10], // CGNAT
|
||||
['224.0.0.0', 4], // multicast
|
||||
['240.0.0.0', 4], // reserved (includes broadcast)
|
||||
] as const) {
|
||||
BLOCKED_IPS.addSubnet(network, prefix, 'ipv4');
|
||||
}
|
||||
|
||||
BLOCKED_IPS.addAddress('::', 'ipv6');
|
||||
BLOCKED_IPS.addAddress('::1', 'ipv6');
|
||||
BLOCKED_IPS.addSubnet('ff00::', 8, 'ipv6'); // multicast
|
||||
BLOCKED_IPS.addSubnet('fc00::', 7, 'ipv6'); // unique local
|
||||
BLOCKED_IPS.addSubnet('fe80::', 10, 'ipv6'); // link-local
|
||||
ALLOWED_IPV6.addSubnet('2000::', 3, 'ipv6'); // global unicast
|
||||
|
||||
function extractEmbeddedIPv4FromIPv6(address: string): string | null {
|
||||
if (!address.includes('.')) {
|
||||
return null;
|
||||
}
|
||||
const idx = address.lastIndexOf(':');
|
||||
if (idx === -1) {
|
||||
return null;
|
||||
}
|
||||
const tail = address.slice(idx + 1);
|
||||
return isIP(tail) === 4 ? tail : null;
|
||||
}
|
||||
|
||||
function isBlockedIpAddress(address: string): boolean {
|
||||
const ip = stripZoneId(address);
|
||||
const family = isIP(ip);
|
||||
if (family === 4) {
|
||||
return BLOCKED_IPS.check(ip, 'ipv4');
|
||||
}
|
||||
if (family === 6) {
|
||||
const embeddedV4 = extractEmbeddedIPv4FromIPv6(ip);
|
||||
if (embeddedV4) {
|
||||
return isBlockedIpAddress(embeddedV4);
|
||||
}
|
||||
if (!ALLOWED_IPV6.check(ip, 'ipv6')) {
|
||||
return true;
|
||||
}
|
||||
return BLOCKED_IPS.check(ip, 'ipv6');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function resolveHostAddresses(hostname: string): Promise<string[]> {
|
||||
const lowered = hostname.toLowerCase();
|
||||
if (lowered === 'localhost' || lowered.endsWith('.localhost')) {
|
||||
return ['127.0.0.1', '::1'];
|
||||
}
|
||||
|
||||
const results = await dns.lookup(hostname, { all: true, verbatim: true });
|
||||
return results.map(r => r.address);
|
||||
}
|
||||
|
||||
export async function resolveAndValidateUrlForPreview(
|
||||
rawUrl: string
|
||||
): Promise<{ url: URL; address: string }> {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(rawUrl);
|
||||
} catch {
|
||||
throw new Error('Invalid URL');
|
||||
}
|
||||
|
||||
if (!ALLOWED_PROTOCOLS.has(url.protocol)) {
|
||||
throw new Error('Disallowed URL protocol');
|
||||
}
|
||||
|
||||
if (url.username || url.password) {
|
||||
throw new Error('URL must not include credentials');
|
||||
}
|
||||
|
||||
if (!url.hostname) {
|
||||
throw new Error('Missing hostname');
|
||||
}
|
||||
|
||||
if (isIP(url.hostname)) {
|
||||
if (isBlockedIpAddress(url.hostname)) {
|
||||
throw new Error('Blocked IP address');
|
||||
}
|
||||
return { url, address: url.hostname };
|
||||
}
|
||||
|
||||
const addresses = await resolveHostAddresses(url.hostname);
|
||||
if (!addresses.length) {
|
||||
throw new Error('Unresolvable hostname');
|
||||
}
|
||||
|
||||
for (const addr of addresses) {
|
||||
if (isBlockedIpAddress(addr)) {
|
||||
throw new Error('Blocked IP address');
|
||||
}
|
||||
}
|
||||
|
||||
return { url, address: addresses[0] };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { isMacOS } from '../../shared/utils';
|
||||
import { persistentConfig } from '../config-storage/persist';
|
||||
import { logger } from '../logger';
|
||||
import { openExternalSafely } from '../security/open-external';
|
||||
import { resolveAndValidateUrlForPreview } from '../security/url-safety';
|
||||
import type { WorkbenchViewMeta } from '../shared-state-schema';
|
||||
import { MenubarStateKey, MenubarStateSchema } from '../shared-state-schema';
|
||||
import { globalStateStorage } from '../shared-storage/storage';
|
||||
@@ -37,6 +38,13 @@ import { getOrCreateCustomThemeWindow } from '../windows-manager/custom-theme-wi
|
||||
import { getChallengeResponse } from './challenge';
|
||||
import { uiSubjects } from './subject';
|
||||
|
||||
const EMPTY_OBJECT = Object.freeze({
|
||||
title: undefined,
|
||||
description: undefined,
|
||||
icon: undefined,
|
||||
image: undefined,
|
||||
});
|
||||
|
||||
const TraySettingsState = {
|
||||
$: globalStateStorage.watch<MenubarStateSchema>(MenubarStateKey).pipe(
|
||||
map(v => MenubarStateSchema.parse(v ?? {})),
|
||||
@@ -127,6 +135,13 @@ export const uiHandlers = {
|
||||
}
|
||||
},
|
||||
getBookmarkDataByLink: async (_, link: string) => {
|
||||
try {
|
||||
// Basic validation up-front to prevent SSRF (including redirects).
|
||||
await resolveAndValidateUrlForPreview(link);
|
||||
} catch {
|
||||
return EMPTY_OBJECT;
|
||||
}
|
||||
|
||||
if (
|
||||
(link.startsWith('https://x.com/') ||
|
||||
link.startsWith('https://www.x.com/') ||
|
||||
@@ -135,8 +150,9 @@ export const uiHandlers = {
|
||||
link.includes('/status/')
|
||||
) {
|
||||
// use api.fxtwitter.com
|
||||
link =
|
||||
'https://api.fxtwitter.com/status/' + /\/status\/(.*)/.exec(link)?.[1];
|
||||
const statusId = /\/status\/(\d+)/.exec(link)?.[1];
|
||||
if (!statusId) return EMPTY_OBJECT;
|
||||
link = `https://api.fxtwitter.com/status/${statusId}`;
|
||||
try {
|
||||
const { tweet } = (await fetch(link).then(res => res.json())) as any;
|
||||
return {
|
||||
@@ -161,7 +177,20 @@ export const uiHandlers = {
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
|
||||
},
|
||||
followRedirects: 'follow',
|
||||
followRedirects: 'manual',
|
||||
handleRedirects: (_baseUrl: string, forwardedUrl: string) => {
|
||||
try {
|
||||
// Only allow http(s) redirects and re-validate before following.
|
||||
const u = new URL(forwardedUrl);
|
||||
return u.protocol === 'http:' || u.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
resolveDNSHost: async (url: string) => {
|
||||
const { address } = await resolveAndValidateUrlForPreview(url);
|
||||
return address;
|
||||
},
|
||||
}).catch(() => {
|
||||
return {
|
||||
title: '',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface AuthenticationRequest {
|
||||
method: 'magic-link' | 'oauth';
|
||||
method: 'magic-link' | 'oauth' | 'open-app-signin';
|
||||
payload: Record<string, any>;
|
||||
server?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
describe('redirect proxy allowlist', () => {
|
||||
it('blocks missing redirect_uri', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'stable';
|
||||
process.env.NODE_ENV = 'production';
|
||||
delete process.env.DEV_SERVER_URL;
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(validateRedirectProxyUrl('assets://./redirect-proxy')).toEqual({
|
||||
allow: false,
|
||||
reason: 'missing_redirect_target',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks untrusted redirect_uri', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'stable';
|
||||
process.env.NODE_ENV = 'production';
|
||||
delete process.env.DEV_SERVER_URL;
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(
|
||||
validateRedirectProxyUrl(
|
||||
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Fevil.com%2F'
|
||||
)
|
||||
).toEqual({
|
||||
allow: false,
|
||||
reason: 'untrusted_redirect_target',
|
||||
redirectTarget: 'https://evil.com/',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows trusted redirect_uri', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'stable';
|
||||
process.env.NODE_ENV = 'production';
|
||||
delete process.env.DEV_SERVER_URL;
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(
|
||||
validateRedirectProxyUrl(
|
||||
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Fgithub.com%2Ftoeverything%2FAFFiNE'
|
||||
)
|
||||
).toEqual({
|
||||
allow: true,
|
||||
redirectTarget: 'https://github.com/toeverything/AFFiNE',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows current hostname (canary)', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'canary';
|
||||
process.env.NODE_ENV = 'production';
|
||||
delete process.env.DEV_SERVER_URL;
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(
|
||||
validateRedirectProxyUrl(
|
||||
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Faffine.fail%2Fpricing'
|
||||
)
|
||||
).toEqual({
|
||||
allow: true,
|
||||
redirectTarget: 'https://affine.fail/pricing',
|
||||
});
|
||||
});
|
||||
|
||||
it('allows current hostname from DEV_SERVER_URL in development', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'stable';
|
||||
process.env.NODE_ENV = 'development';
|
||||
process.env.DEV_SERVER_URL = 'http://localhost:8080';
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(
|
||||
validateRedirectProxyUrl(
|
||||
'assets://./redirect-proxy?redirect_uri=http%3A%2F%2Flocalhost%3A1234%2Fauth'
|
||||
)
|
||||
).toEqual({
|
||||
allow: true,
|
||||
redirectTarget: 'http://localhost:1234/auth',
|
||||
});
|
||||
});
|
||||
|
||||
it('blocks redirect_uri in hash when untrusted', async () => {
|
||||
vi.resetModules();
|
||||
process.env.BUILD_TYPE = 'stable';
|
||||
process.env.NODE_ENV = 'production';
|
||||
delete process.env.DEV_SERVER_URL;
|
||||
|
||||
const { validateRedirectProxyUrl } =
|
||||
await import('../../src/main/security/redirect-proxy');
|
||||
expect(
|
||||
validateRedirectProxyUrl(
|
||||
'assets://./redirect-proxy#/foo?redirect_uri=https%3A%2F%2Fevil.com%2F'
|
||||
)
|
||||
).toEqual({
|
||||
allow: false,
|
||||
reason: 'untrusted_redirect_target',
|
||||
redirectTarget: 'https://evil.com/',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,7 @@ public class AuthPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
} else {
|
||||
call.reject("Failed to sign in")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let token = try self.tokenFromCookie(endpoint) else {
|
||||
@@ -57,6 +58,7 @@ public class AuthPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
} else {
|
||||
call.reject("Failed to sign in")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let token = try self.tokenFromCookie(endpoint) else {
|
||||
@@ -91,6 +93,7 @@ public class AuthPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
} else {
|
||||
call.reject("Failed to sign in")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
guard let token = try self.tokenFromCookie(endpoint) else {
|
||||
@@ -109,20 +112,24 @@ public class AuthPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
Task {
|
||||
do {
|
||||
let endpoint = try call.getStringEnsure("endpoint")
|
||||
let csrfToken = try self.csrfTokenFromCookie(endpoint)
|
||||
|
||||
let (data, response) = try await self.fetch(endpoint, method: "GET", action: "/api/auth/sign-out", headers: [:], body: nil)
|
||||
let (data, response) = try await self.fetch(endpoint, method: "POST", action: "/api/auth/sign-out", headers: [
|
||||
"x-affine-csrf-token": csrfToken,
|
||||
], body: nil)
|
||||
|
||||
if response.statusCode >= 400 {
|
||||
if let textBody = String(data: data, encoding: .utf8) {
|
||||
call.reject(textBody)
|
||||
} else {
|
||||
call.reject("Failed to sign in")
|
||||
call.reject("Failed to sign out")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
call.resolve(["ok": true])
|
||||
} catch {
|
||||
call.reject("Failed to sign in, \(error)", nil, error)
|
||||
call.reject("Failed to sign out, \(error)", nil, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,6 +148,16 @@ public class AuthPlugin: CAPPlugin, CAPBridgedPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
private func csrfTokenFromCookie(_ endpoint: String) throws -> String? {
|
||||
guard let endpointUrl = URL(string: endpoint) else {
|
||||
throw AuthError.invalidEndpoint
|
||||
}
|
||||
|
||||
return HTTPCookieStorage.shared.cookies(for: endpointUrl)?.first(where: {
|
||||
$0.name == "affine_csrf_token"
|
||||
})?.value
|
||||
}
|
||||
|
||||
private func fetch(_ endpoint: String, method: String, action: String, headers: [String: String?], body: Encodable?) async throws -> (Data, HTTPURLResponse) {
|
||||
guard let targetUrl = URL(string: "\(endpoint)\(action)") else {
|
||||
throw AuthError.invalidEndpoint
|
||||
|
||||
@@ -125,16 +125,6 @@ export const OnboardingPage = ({
|
||||
return null;
|
||||
}
|
||||
|
||||
// deprecated
|
||||
// TODO(@forehalo): remove
|
||||
if (callbackUrl?.startsWith('/open-app/signin-redirect')) {
|
||||
const url = new URL(callbackUrl, window.location.origin);
|
||||
url.searchParams.set('next', 'onboarding');
|
||||
console.log('redirect to', url.toString());
|
||||
window.location.assign(url.toString());
|
||||
return null;
|
||||
}
|
||||
|
||||
if (question) {
|
||||
return (
|
||||
<ScrollableLayout
|
||||
|
||||
@@ -91,7 +91,7 @@
|
||||
"semver": "^7.7.3",
|
||||
"ses": "^1.14.0",
|
||||
"shiki": "^3.19.0",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"swr": "^2.3.7",
|
||||
"tinykeys": "patch:tinykeys@npm%3A2.1.0#~/.yarn/patches/tinykeys-npm-2.1.0-819feeaed0.patch",
|
||||
"y-protocols": "^1.0.6",
|
||||
|
||||
@@ -14,6 +14,23 @@ import { z } from 'zod';
|
||||
import { supportedClient } from './common';
|
||||
|
||||
const supportedProvider = z.nativeEnum(OAuthProviderType);
|
||||
const CSRF_COOKIE_NAME = 'affine_csrf_token';
|
||||
|
||||
function getCookieValue(name: string) {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cookies = document.cookie ? document.cookie.split('; ') : [];
|
||||
for (const cookie of cookies) {
|
||||
const idx = cookie.indexOf('=');
|
||||
const key = idx === -1 ? cookie : cookie.slice(0, idx);
|
||||
if (key === name) {
|
||||
return idx === -1 ? '' : cookie.slice(idx + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const oauthParameters = z.object({
|
||||
provider: supportedProvider,
|
||||
@@ -36,7 +53,11 @@ export const loader: LoaderFunction = async ({ request }) => {
|
||||
|
||||
// sign out first, web only
|
||||
if (client === 'web') {
|
||||
await fetch('/api/auth/sign-out');
|
||||
const csrfToken = getCookieValue(CSRF_COOKIE_NAME);
|
||||
await fetch('/api/auth/sign-out', {
|
||||
method: 'POST',
|
||||
headers: csrfToken ? { 'x-affine-csrf-token': csrfToken } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const paramsParseResult = oauthParameters.safeParse({
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { useNavigateHelper } from '@affine/core/components/hooks/use-navigate-helper';
|
||||
import { GraphQLService } from '@affine/core/modules/cloud';
|
||||
import { AuthService } from '@affine/core/modules/cloud';
|
||||
import { OpenInAppPage } from '@affine/core/modules/open-in-app/views/open-in-app-page';
|
||||
import {
|
||||
appSchemaUrl,
|
||||
appSchemes,
|
||||
channelToScheme,
|
||||
} from '@affine/core/utils/channel';
|
||||
import type { GetCurrentUserQuery } from '@affine/graphql';
|
||||
import { getCurrentUserQuery } from '@affine/graphql';
|
||||
import { useService } from '@toeverything/infra';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { AppContainer } from '../../components/app-container';
|
||||
@@ -49,38 +47,43 @@ const OpenUrl = () => {
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
const OpenOAuthJwt = () => {
|
||||
const [currentUser, setCurrentUser] = useState<
|
||||
GetCurrentUserQuery['currentUser'] | null
|
||||
>(null);
|
||||
const OpenAppSignInRedirect = () => {
|
||||
const authService = useService(AuthService);
|
||||
const [params] = useSearchParams();
|
||||
const graphqlService = useService(GraphQLService);
|
||||
const triggeredRef = useRef(false);
|
||||
const [urlToOpen, setUrlToOpen] = useState<string | null>(null);
|
||||
|
||||
const maybeScheme = appSchemes.safeParse(params.get('scheme'));
|
||||
const scheme = maybeScheme.success
|
||||
? maybeScheme.data
|
||||
: channelToScheme[BUILD_CONFIG.appBuildType];
|
||||
const next = params.get('next') || '';
|
||||
const next = params.get('next') || undefined;
|
||||
|
||||
useEffect(() => {
|
||||
graphqlService
|
||||
.gql({
|
||||
query: getCurrentUserQuery,
|
||||
})
|
||||
.then(res => {
|
||||
setCurrentUser(res?.currentUser || null);
|
||||
if (triggeredRef.current) {
|
||||
return;
|
||||
}
|
||||
triggeredRef.current = true;
|
||||
|
||||
authService
|
||||
.createOpenAppSignInCode()
|
||||
.then(code => {
|
||||
const authParams = new URLSearchParams();
|
||||
authParams.set('method', 'open-app-signin');
|
||||
authParams.set(
|
||||
'payload',
|
||||
JSON.stringify(next ? { code, next } : { code })
|
||||
);
|
||||
authParams.set('server', location.origin);
|
||||
setUrlToOpen(`${scheme}://authentication?${authParams.toString()}`);
|
||||
})
|
||||
.catch(console.error);
|
||||
}, [graphqlService]);
|
||||
}, [authService, next, scheme]);
|
||||
|
||||
if (!currentUser || !currentUser?.token?.sessionToken) {
|
||||
if (!urlToOpen) {
|
||||
return <AppContainer fallback />;
|
||||
}
|
||||
|
||||
const urlToOpen = `${scheme}://signin-redirect?token=${
|
||||
currentUser.token.sessionToken
|
||||
}&next=${next}`;
|
||||
|
||||
return <OpenInAppPage urlToOpen={urlToOpen} />;
|
||||
};
|
||||
|
||||
@@ -91,7 +94,7 @@ export const Component = () => {
|
||||
if (action === 'url') {
|
||||
return <OpenUrl />;
|
||||
} else if (action === 'signin-redirect') {
|
||||
return <OpenOAuthJwt />;
|
||||
return <OpenAppSignInRedirect />;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -1,21 +1,8 @@
|
||||
import { DebugLogger } from '@affine/debug';
|
||||
import { escapeRegExp } from 'lodash-es';
|
||||
import { isAllowedRedirectTarget } from '@toeverything/infra';
|
||||
import { type LoaderFunction, Navigate, useLoaderData } from 'react-router-dom';
|
||||
|
||||
const trustedDomain = [
|
||||
'google.com',
|
||||
'stripe.com',
|
||||
'github.com',
|
||||
'twitter.com',
|
||||
'discord.gg',
|
||||
'youtube.com',
|
||||
't.me',
|
||||
'reddit.com',
|
||||
'affine.pro',
|
||||
];
|
||||
|
||||
const logger = new DebugLogger('redirect_proxy');
|
||||
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
|
||||
|
||||
/**
|
||||
* /redirect-proxy page
|
||||
@@ -31,26 +18,13 @@ export const loader: LoaderFunction = async ({ request }) => {
|
||||
return { allow: false };
|
||||
}
|
||||
|
||||
try {
|
||||
const target = new URL(redirectUri);
|
||||
|
||||
if (!ALLOWED_PROTOCOLS.has(target.protocol)) {
|
||||
logger.warn('Blocked redirect with disallowed protocol', target.protocol);
|
||||
return { allow: false };
|
||||
}
|
||||
|
||||
if (
|
||||
target.hostname === window.location.hostname ||
|
||||
trustedDomain.some(domain =>
|
||||
new RegExp(`(^|\\.)${escapeRegExp(domain)}$`).test(target.hostname)
|
||||
)
|
||||
) {
|
||||
location.href = redirectUri;
|
||||
return { allow: true };
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('Failed to parse redirect uri', e);
|
||||
return { allow: false };
|
||||
if (
|
||||
isAllowedRedirectTarget(redirectUri, {
|
||||
currentHostname: window.location.hostname,
|
||||
})
|
||||
) {
|
||||
location.href = redirectUri;
|
||||
return { allow: true };
|
||||
}
|
||||
|
||||
logger.warn('Blocked redirect to untrusted domain', redirectUri);
|
||||
|
||||
@@ -4,6 +4,24 @@ import { AuthProvider } from '../provider/auth';
|
||||
import { ServerScope } from '../scopes/server';
|
||||
import { FetchService } from '../services/fetch';
|
||||
|
||||
const CSRF_COOKIE_NAME = 'affine_csrf_token';
|
||||
|
||||
function getCookieValue(name: string) {
|
||||
if (typeof document === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cookies = document.cookie ? document.cookie.split('; ') : [];
|
||||
for (const cookie of cookies) {
|
||||
const idx = cookie.indexOf('=');
|
||||
const key = idx === -1 ? cookie : cookie.slice(0, idx);
|
||||
if (key === name) {
|
||||
return idx === -1 ? '' : cookie.slice(idx + 1);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function configureDefaultAuthProvider(framework: Framework) {
|
||||
framework.scope(ServerScope).override(AuthProvider, resolver => {
|
||||
const fetchService = resolver.get(FetchService);
|
||||
@@ -62,7 +80,11 @@ export function configureDefaultAuthProvider(framework: Framework) {
|
||||
});
|
||||
},
|
||||
async signOut() {
|
||||
await fetchService.fetch('/api/auth/sign-out');
|
||||
const csrfToken = getCookieValue(CSRF_COOKIE_NAME);
|
||||
await fetchService.fetch('/api/auth/sign-out', {
|
||||
method: 'POST',
|
||||
headers: csrfToken ? { 'x-affine-csrf-token': csrfToken } : undefined,
|
||||
});
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -165,6 +165,32 @@ export class AuthService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
async createOpenAppSignInCode() {
|
||||
const res = await this.fetchService.fetch(
|
||||
'/api/auth/open-app/sign-in-code',
|
||||
{
|
||||
method: 'POST',
|
||||
}
|
||||
);
|
||||
const body = (await res.json()) as { code?: string };
|
||||
|
||||
if (!body.code) {
|
||||
throw new Error('Missing open-app sign-in code');
|
||||
}
|
||||
|
||||
return body.code;
|
||||
}
|
||||
|
||||
async signInOpenAppSignInCode(code: string) {
|
||||
await this.fetchService.fetch('/api/auth/open-app/sign-in', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
|
||||
this.session.revalidate();
|
||||
}
|
||||
|
||||
async signInPassword(credential: {
|
||||
email: string;
|
||||
password: string;
|
||||
|
||||
@@ -146,6 +146,14 @@ export class DesktopApiService extends Service {
|
||||
await authService.signInOauth(code, state, provider);
|
||||
break;
|
||||
}
|
||||
case 'open-app-signin': {
|
||||
const code = (payload as { code?: unknown }).code;
|
||||
if (typeof code !== 'string' || !code) {
|
||||
throw new Error('Invalid open-app sign-in payload');
|
||||
}
|
||||
await authService.signInOpenAppSignInCode(code);
|
||||
break;
|
||||
}
|
||||
}
|
||||
})().catch(e => {
|
||||
notify.error({
|
||||
|
||||
@@ -9,16 +9,16 @@
|
||||
"es-CL": 99,
|
||||
"es": 98,
|
||||
"fa": 98,
|
||||
"fr": 100,
|
||||
"fr": 99,
|
||||
"hi": 2,
|
||||
"it-IT": 100,
|
||||
"it-IT": 99,
|
||||
"it": 1,
|
||||
"ja": 98,
|
||||
"ko": 99,
|
||||
"nb-NO": 48,
|
||||
"pl": 100,
|
||||
"pt-BR": 98,
|
||||
"ru": 100,
|
||||
"ru": 99,
|
||||
"sv-SE": 98,
|
||||
"uk": 98,
|
||||
"ur": 2,
|
||||
|
||||
@@ -8504,6 +8504,17 @@ export function useAFFiNEI18N(): {
|
||||
["error.HTTP_REQUEST_ERROR"](options: {
|
||||
readonly message: string;
|
||||
}): string;
|
||||
/**
|
||||
* `Invalid URL`
|
||||
*/
|
||||
["error.SSRF_BLOCKED_ERROR"](): string;
|
||||
/**
|
||||
* `Response too large ({{receivedBytes}} bytes), limit is {{limitBytes}} bytes`
|
||||
*/
|
||||
["error.RESPONSE_TOO_LARGE_ERROR"](options: Readonly<{
|
||||
receivedBytes: string;
|
||||
limitBytes: string;
|
||||
}>): string;
|
||||
/**
|
||||
* `Email service is not configured.`
|
||||
*/
|
||||
|
||||
@@ -2131,6 +2131,8 @@
|
||||
"error.BAD_REQUEST": "Bad request.",
|
||||
"error.GRAPHQL_BAD_REQUEST": "GraphQL bad request, code: {{code}}, {{message}}",
|
||||
"error.HTTP_REQUEST_ERROR": "HTTP request error, message: {{message}}",
|
||||
"error.SSRF_BLOCKED_ERROR": "Invalid URL",
|
||||
"error.RESPONSE_TOO_LARGE_ERROR": "Response too large ({{receivedBytes}} bytes), limit is {{limitBytes}} bytes",
|
||||
"error.EMAIL_SERVICE_NOT_CONFIGURED": "Email service is not configured.",
|
||||
"error.QUERY_TOO_LONG": "Query is too long, max length is {{max}}.",
|
||||
"error.VALIDATION_ERROR": "Validation error, errors: {{errors}}",
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
"react-dom": "^19.2.1",
|
||||
"react-markdown": "^10.1.0",
|
||||
"socket.io": "^4.7.4",
|
||||
"socket.io-client": "^4.7.4",
|
||||
"socket.io-client": "^4.8.3",
|
||||
"swr": "^2.3.7",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"tsx": "^4.19.2",
|
||||
|
||||
Reference in New Issue
Block a user