mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-09-22 19:53:48 +08:00
chore: drop old client support (#14369)
This commit is contained in:
+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
|
||||
|
||||
Reference in New Issue
Block a user