mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-11-30 01:00:27 +03:00
fix(android): allow plain http only to local network servers (#15925)
Release builds of the Android app set `usesCleartextTraffic=false` and `MIXED_CONTENT_NEVER_ALLOW` (#15118), so the app could not reach a self-hosted server over http at all, including one on the local network. This allows plain-text http/ws only to local network hosts, matching iOS `NSAllowsLocalNetworking`: - unqualified single-label names (`nas`, `localhost`) and `.local` names - loopback, private and link-local IP literals: 127/8, 10/8, 172.16/12, 192.168/16, 169.254/16, `::1`, fc00::/7, fe80::/10 Anything else is refused, including public-looking names that resolve to a private address (names are never resolved). Android WebView cannot allow mixed content per host: the app runs at `https://localhost`, so every http/ws request is mixed content, `mixedContentMode` is WebView-wide, and WebView only honours the app-wide cleartext flag. So cleartext and `MIXED_CONTENT_ALWAYS_ALLOW` are enabled globally, and the rule is enforced in three places with the same host check: - `AffineWebViewClient.shouldInterceptRequest` answers plain http requests to other hosts with a 403. - The web app wraps `WebSocket` and `fetch` (main thread and the nbstore worker), because WebView request interception never sees WebSocket handshakes. This is where the sync `ws://` connection is refused. - An OkHttp interceptor rejects plain http to other hosts for the native clients (GraphQL, SSE, auth). On Android and iOS, the add-server step rejects public `http://` addresses with a message asking for an https address, a local IP or a `.local` name. The host check exists in TS (`@affine/core/utils/local-network`) and Kotlin (`LocalNetwork.kt`); both are tested against the same table, `core/src/utils/local-network/fixtures/hosts.json` (the Android unit tests read it as a test resource). Other tests show public `http://` and `ws://` are blocked in the web guard and in an OkHttp client, while LAN, `.local` and https pass. #15509 (server on a LAN IP) is fixed by this. The setup in #15438 (`http://affine.home.com`) stays blocked, as it is on iOS: that server needs https, a local IP address or a `.local` name. Tested: the TS tests with vitest, the Kotlin tests with JUnit outside Gradle (Kotlin 2.2.20, JDK 21). Not run on a device or emulator; the WebView and WebSocket behaviour is covered by unit tests only. fix #15438 fix #15509 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Android now allows HTTP connections to servers on the local network, while blocking insecure connections to public servers. HTTPS connections remain available. * When adding a self-hosted server on Android or iOS, you’ll see guidance if its public address uses HTTP. Use an HTTPS address or a local network address instead. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: DarkSky <darksky2048@gmail.com>
This commit is contained in:
1 parent
89bdb9c1e9
commit
c91b08fbcc
18 files changed
+564
-10
No files matched your search
@@ -30,7 +30,6 @@ android {
|
||||
versionCode = 1
|
||||
versionName = System.getenv('VERSION_NAME') ?: 'v1.0.0-local'
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
manifestPlaceholders = [usesCleartextTraffic: "false"]
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||
@@ -60,7 +59,6 @@ android {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
debuggable true
|
||||
manifestPlaceholders = [usesCleartextTraffic: "true"]
|
||||
}
|
||||
}
|
||||
flavorDimensions = ['chanel']
|
||||
@@ -71,6 +69,11 @@ android {
|
||||
canary
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
// Host classification cases shared with the web app's local-network check.
|
||||
test.resources.srcDirs += '../../../../core/src/utils/local-network/fixtures'
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:hardwareAccelerated="true"
|
||||
android:supportsRtl="true"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<activity
|
||||
|
||||
+12
@@ -1,7 +1,9 @@
|
||||
package app.affine.pro
|
||||
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import app.affine.pro.utils.LocalNetwork
|
||||
import com.getcapacitor.Bridge
|
||||
import com.getcapacitor.BridgeWebViewClient
|
||||
|
||||
@@ -9,6 +11,16 @@ internal class AffineWebViewClient(
|
||||
bridge: Bridge,
|
||||
private val trustedOrigin: String?,
|
||||
) : BridgeWebViewClient(bridge) {
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
): WebResourceResponse? {
|
||||
if (LocalNetwork.blocksCleartext(request.url.scheme, request.url.host)) {
|
||||
return WebResourceResponse("text/plain", "utf-8", 403, "Forbidden", emptyMap(), null)
|
||||
}
|
||||
return super.shouldInterceptRequest(view, request)
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
|
||||
@@ -137,13 +137,10 @@ class MainActivity : BridgeActivity(), AIButtonPlugin.Callback, AFFiNEThemePlugi
|
||||
isHorizontalScrollBarEnabled = false
|
||||
isVerticalScrollBarEnabled = false
|
||||
settings.apply {
|
||||
// Debug builds may point CAP_SERVER_URL at an HTTP dev server; release builds
|
||||
// should keep mixed content blocked.
|
||||
mixedContentMode = if (BuildConfig.DEBUG) {
|
||||
WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
|
||||
} else {
|
||||
WebSettings.MIXED_CONTENT_NEVER_ALLOW
|
||||
}
|
||||
// Self-hosted servers on the local network may only speak http. Mixed content
|
||||
// cannot be allowed per host, so AffineWebViewClient and the web app's
|
||||
// cleartext guard refuse plain-text requests to hosts outside the local network.
|
||||
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
|
||||
setSupportZoom(false)
|
||||
builtInZoomControls = false
|
||||
displayZoomControls = false
|
||||
|
||||
@@ -2,6 +2,7 @@ package app.affine.pro.service
|
||||
|
||||
import app.affine.pro.AFFiNEApp
|
||||
import app.affine.pro.CapacitorConfig
|
||||
import app.affine.pro.utils.LocalNetwork
|
||||
import app.affine.pro.utils.dataStore
|
||||
import app.affine.pro.utils.del
|
||||
import app.affine.pro.utils.set
|
||||
@@ -34,6 +35,7 @@ object OkHttp {
|
||||
CookieStore.saveCookies(url.host, cookies)
|
||||
}
|
||||
})
|
||||
.addInterceptor(LocalNetwork.cleartextGuard)
|
||||
.addInterceptor {
|
||||
it.proceed(
|
||||
it.request()
|
||||
@@ -54,6 +56,7 @@ object OkHttp {
|
||||
object AuthHttp {
|
||||
val client = OkHttpClient.Builder()
|
||||
.cookieJar(CookieJar.NO_COOKIES)
|
||||
.addInterceptor(LocalNetwork.cleartextGuard)
|
||||
.addInterceptor {
|
||||
it.proceed(
|
||||
it.request()
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package app.affine.pro.utils
|
||||
|
||||
import okhttp3.Interceptor
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Plain-text (http, ws) traffic is only allowed to hosts on the local network,
|
||||
* matching iOS NSAllowsLocalNetworking: unqualified names, `.local` names, and
|
||||
* loopback, private and link-local IP literals. Names are never resolved, so a
|
||||
* public-looking name is rejected even if it points to a private address.
|
||||
*
|
||||
* The web app enforces the same rules in `@affine/core/utils/local-network`;
|
||||
* both are tested against its `fixtures/hosts.json`.
|
||||
*/
|
||||
object LocalNetwork {
|
||||
|
||||
private val IPV4_LIKE_LABEL = Regex("^(?:0x[0-9a-f]*|\\d+)$")
|
||||
private val IPV4_LITERAL = Regex("^(?:0|[1-9]\\d{0,2})(?:\\.(?:0|[1-9]\\d{0,2})){3}$")
|
||||
private val IPV6_GROUP = Regex("^[0-9a-f]{1,4}$")
|
||||
|
||||
fun isLocalHost(host: String): Boolean {
|
||||
val name = host.lowercase().removeSurrounding("[", "]").removeSuffix(".")
|
||||
if (':' in name) return isLocalIPv6(name)
|
||||
val labels = name.split('.')
|
||||
if (labels.any { it.isEmpty() }) return false
|
||||
if (IPV4_LIKE_LABEL.matches(labels.last())) return isLocalIPv4(name)
|
||||
return labels.size == 1 || labels.last() == "local"
|
||||
}
|
||||
|
||||
fun blocksCleartext(scheme: String?, host: String?): Boolean {
|
||||
val plainText = scheme.equals("http", ignoreCase = true) ||
|
||||
scheme.equals("ws", ignoreCase = true)
|
||||
return plainText && (host == null || !isLocalHost(host))
|
||||
}
|
||||
|
||||
/** Rejects plain-text requests to hosts outside the local network. */
|
||||
val cleartextGuard = Interceptor { chain ->
|
||||
val url = chain.request().url
|
||||
if (blocksCleartext(url.scheme, url.host)) {
|
||||
throw IOException(
|
||||
"Plain-text connection to ${url.host} is blocked: only local network servers may use http"
|
||||
)
|
||||
}
|
||||
chain.proceed(chain.request())
|
||||
}
|
||||
|
||||
private fun isLocalIPv4(address: String): Boolean {
|
||||
if (!IPV4_LITERAL.matches(address)) return false
|
||||
val octets = address.split('.').map { it.toInt() }
|
||||
if (octets.any { it > 255 }) return false
|
||||
val (a, b) = octets
|
||||
return a == 127 ||
|
||||
a == 10 ||
|
||||
(a == 172 && b in 16..31) ||
|
||||
(a == 192 && b == 168) ||
|
||||
(a == 169 && b == 254)
|
||||
}
|
||||
|
||||
private fun parseIPv6(address: String): List<Int>? {
|
||||
val halves = address.split("::")
|
||||
if (halves.size > 2) return null
|
||||
val head = if (halves[0].isEmpty()) emptyList() else halves[0].split(':')
|
||||
val tail = if (halves.size == 2 && halves[1].isNotEmpty()) halves[1].split(':') else emptyList()
|
||||
val missing = 8 - head.size - tail.size
|
||||
if (if (halves.size == 1) missing != 0 else missing < 1) return null
|
||||
val groups = head + List(if (halves.size == 2) missing else 0) { "0" } + tail
|
||||
if (!groups.all { IPV6_GROUP.matches(it) }) return null
|
||||
return groups.map { it.toInt(16) }
|
||||
}
|
||||
|
||||
private fun isLocalIPv6(address: String): Boolean {
|
||||
val groups = parseIPv6(address.substringBefore('%')) ?: return false
|
||||
val isLoopback = groups.take(7).all { it == 0 } && groups[7] == 1
|
||||
return isLoopback ||
|
||||
(groups[0] and 0xfe00) == 0xfc00 ||
|
||||
(groups[0] and 0xffc0) == 0xfe80
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package app.affine.pro.utils
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.boolean
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Protocol
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
|
||||
class LocalNetworkTest {
|
||||
|
||||
@Test
|
||||
fun classifiesHostsLikeTheWebApp() {
|
||||
val fixture = javaClass.classLoader!!.getResource("hosts.json")!!.readText()
|
||||
val mismatches = Json.parseToJsonElement(fixture).jsonArray
|
||||
.map { it.jsonObject }
|
||||
.map { it["host"]!!.jsonPrimitive.content to it["local"]!!.jsonPrimitive.boolean }
|
||||
.filter { (host, local) -> LocalNetwork.isLocalHost(host) != local }
|
||||
assertEquals(emptyList<Pair<String, Boolean>>(), mismatches)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun okHttpGuardBlocksPublicHttpOnly() {
|
||||
val client = OkHttpClient.Builder()
|
||||
.addInterceptor(LocalNetwork.cleartextGuard)
|
||||
.addInterceptor { chain ->
|
||||
Response.Builder()
|
||||
.request(chain.request())
|
||||
.protocol(Protocol.HTTP_1_1)
|
||||
.code(200)
|
||||
.message("OK")
|
||||
.body("".toResponseBody())
|
||||
.build()
|
||||
}
|
||||
.build()
|
||||
fun get(url: String) = client.newCall(Request.Builder().url(url).build()).execute().code
|
||||
|
||||
assertThrows(IOException::class.java) { get("http://affine.home.com/graphql") }
|
||||
assertEquals(200, get("http://192.168.1.10:3010/graphql"))
|
||||
assertEquals(200, get("http://nas.local/graphql"))
|
||||
assertEquals(200, get("https://affine.home.com/graphql"))
|
||||
}
|
||||
}
|
||||
@@ -1 +1,5 @@
|
||||
import '@affine/core/bootstrap/browser';
|
||||
|
||||
import { installCleartextGuard } from '@affine/core/utils/local-network/cleartext-guard';
|
||||
|
||||
installCleartextGuard(globalThis);
|
||||
@@ -3,8 +3,11 @@ import '@affine/component/theme';
|
||||
import '@affine/core/mobile/styles/mobile.css';
|
||||
import './proxy';
|
||||
|
||||
import { installCleartextGuard } from '@affine/core/utils/local-network/cleartext-guard';
|
||||
import { viewportRuntimeConfig } from '@blocksuite/affine/std/gfx';
|
||||
|
||||
installCleartextGuard(globalThis);
|
||||
|
||||
// Android WebView is less prone to the iOS WKWebView process kill, so keep the
|
||||
// user-facing zoom range unchanged. These knobs only reduce gesture-time work
|
||||
// and low-zoom canvas memory while preserving the normal-zoom render quality.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@affine/component/auth-components';
|
||||
import { useAsyncCallback } from '@affine/core/components/hooks/affine-async-hooks';
|
||||
import { ServersService } from '@affine/core/modules/cloud';
|
||||
import { isBlockedCleartextUrl } from '@affine/core/utils/local-network';
|
||||
import { UserFriendlyError } from '@affine/error';
|
||||
import { Trans, useI18n } from '@affine/i18n';
|
||||
import { useService } from '@toeverything/infra';
|
||||
@@ -64,6 +65,15 @@ export const AddSelfhostedStep = ({
|
||||
);
|
||||
|
||||
const onConnect = useAsyncCallback(async () => {
|
||||
// The mobile apps only allow plain http to servers on the local network.
|
||||
if (
|
||||
(BUILD_CONFIG.isAndroid || BUILD_CONFIG.isIOS) &&
|
||||
isBlockedCleartextUrl(new URL(normalizeURL(baseURL)))
|
||||
) {
|
||||
setError(true);
|
||||
setErrorHint(t['com.affine.auth.sign.add-selfhosted.public-http']());
|
||||
return;
|
||||
}
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const server = await serversService.addOrGetServerByBaseUrl(
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { installCleartextGuard } from './cleartext-guard';
|
||||
|
||||
function createScope() {
|
||||
class FakeWebSocket {
|
||||
constructor(readonly url: string | URL) {}
|
||||
}
|
||||
const fetch = vi.fn(() => Promise.resolve(new Response()));
|
||||
const scope = {
|
||||
WebSocket: FakeWebSocket as unknown as typeof WebSocket,
|
||||
fetch: fetch as unknown as typeof globalThis.fetch,
|
||||
location: { href: 'https://localhost/' } as Location,
|
||||
};
|
||||
installCleartextGuard(scope);
|
||||
return { scope, fetch };
|
||||
}
|
||||
|
||||
describe('installCleartextGuard', () => {
|
||||
test.each([
|
||||
{ url: 'ws://affine.home.com/socket.io/', blocked: true },
|
||||
{ url: 'ws://192.168.1.10:3010/socket.io/', blocked: false },
|
||||
{ url: 'ws://nas.local/socket.io/', blocked: false },
|
||||
{ url: 'wss://affine.home.com/socket.io/', blocked: false },
|
||||
])('WebSocket to $url is blocked: $blocked', ({ url, blocked }) => {
|
||||
const { scope } = createScope();
|
||||
const open = () => new scope.WebSocket(url);
|
||||
if (blocked) {
|
||||
expect(open).toThrow(DOMException);
|
||||
} else {
|
||||
expect(open().url).toBe(url);
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ url: 'http://affine.home.com/graphql', blocked: true },
|
||||
{ url: 'http://192.168.1.10:3010/graphql', blocked: false },
|
||||
{ url: 'http://localhost:3010/graphql', blocked: false },
|
||||
{ url: 'https://affine.home.com/graphql', blocked: false },
|
||||
{ url: '/graphql', blocked: false },
|
||||
])('fetch to $url is blocked: $blocked', async ({ url, blocked }) => {
|
||||
const { scope, fetch } = createScope();
|
||||
const request = scope.fetch(url);
|
||||
if (blocked) {
|
||||
await expect(request).rejects.toThrow(TypeError);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
} else {
|
||||
await expect(request).resolves.toBeInstanceOf(Response);
|
||||
expect(fetch).toHaveBeenCalledWith(url, undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { isBlockedCleartextUrl } from '.';
|
||||
|
||||
type GuardedScope = Pick<typeof globalThis, 'WebSocket' | 'fetch' | 'location'>;
|
||||
|
||||
// The WebView has to allow mixed content for local http servers, and the
|
||||
// native request interception never sees WebSocket handshakes (nor, depending
|
||||
// on the WebView version, worker requests), so plain-text connections to public
|
||||
// hosts are refused here as well.
|
||||
export function installCleartextGuard(scope: GuardedScope) {
|
||||
const resolve = (url: string | URL) => new URL(url, scope.location.href);
|
||||
const message = (url: URL) =>
|
||||
`Plain-text connection to ${url.host} is blocked: only local network servers may use ${url.protocol.slice(0, -1)}.`;
|
||||
|
||||
const NativeWebSocket = scope.WebSocket;
|
||||
scope.WebSocket = class extends NativeWebSocket {
|
||||
constructor(url: string | URL, protocols?: string | string[]) {
|
||||
const target = resolve(url);
|
||||
if (isBlockedCleartextUrl(target)) {
|
||||
throw new DOMException(message(target), 'SecurityError');
|
||||
}
|
||||
super(url, protocols);
|
||||
}
|
||||
};
|
||||
|
||||
const nativeFetch = scope.fetch;
|
||||
scope.fetch = (input, init) => {
|
||||
const target = resolve(input instanceof Request ? input.url : input);
|
||||
if (isBlockedCleartextUrl(target)) {
|
||||
return Promise.reject(new TypeError(message(target)));
|
||||
}
|
||||
return nativeFetch.call(scope, input, init);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
[
|
||||
{
|
||||
"host": "localhost",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "LOCALHOST",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "localhost.",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "nas",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "my-server",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "local",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "affine.local",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "nas.home.local",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "AFFINE.LOCAL",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "affine.home.com",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "example.com",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "app.affine.pro",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "foo.localhost",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "local.example.com",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "127.0.0.1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "127.255.0.1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "10.0.0.5",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "172.16.0.1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "172.31.255.255",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "192.168.1.10",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "169.254.10.20",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "172.15.0.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "172.32.0.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "192.169.1.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "8.8.8.8",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "100.64.0.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "0.0.0.0",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "2130706433",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "0x7f000001",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "010.0.0.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "256.1.1.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "1.2.3",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "::1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "[::1]",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "0:0:0:0:0:0:0:1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "fe80::1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "[fe80::1]",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "febf::1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "fc00::1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "fd12:3456::1",
|
||||
"local": true
|
||||
},
|
||||
{
|
||||
"host": "fec0::1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "fe00::1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "::",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "2001:4860:4860::8888",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "::ffff:192.168.1.1",
|
||||
"local": false
|
||||
},
|
||||
{
|
||||
"host": "1::2::3",
|
||||
"local": false
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { isBlockedCleartextUrl, isLocalNetworkHost } from '.';
|
||||
import hosts from './fixtures/hosts.json';
|
||||
|
||||
describe('isLocalNetworkHost', () => {
|
||||
test.each(hosts)('$host is local: $local', ({ host, local }) => {
|
||||
expect(isLocalNetworkHost(host)).toBe(local);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isBlockedCleartextUrl', () => {
|
||||
test.each([
|
||||
{ url: 'http://affine.home.com/', blocked: true },
|
||||
{ url: 'ws://example.com/socket.io/', blocked: true },
|
||||
{ url: 'http://192.168.1.10:3010/', blocked: false },
|
||||
{ url: 'ws://nas.local:3010/socket.io/', blocked: false },
|
||||
{ url: 'http://[fe80::1]/', blocked: false },
|
||||
{ url: 'https://affine.home.com/', blocked: false },
|
||||
{ url: 'wss://example.com/', blocked: false },
|
||||
])('$url is blocked: $blocked', ({ url, blocked }) => {
|
||||
expect(isBlockedCleartextUrl(new URL(url))).toBe(blocked);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
// Plain-text (http:, ws:) traffic is only allowed to hosts on the local
|
||||
// network, matching iOS NSAllowsLocalNetworking: unqualified names, `.local`
|
||||
// names, and loopback, private and link-local IP literals. Names are never
|
||||
// resolved, so a public-looking name is rejected even if it points to a
|
||||
// private address. The Android app enforces the same rules natively in
|
||||
// `LocalNetwork.kt`; both are tested against `fixtures/hosts.json`.
|
||||
|
||||
const IPV4_LIKE_LABEL = /^(?:0x[0-9a-f]*|\d+)$/;
|
||||
const IPV4_LITERAL = /^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/;
|
||||
const IPV6_GROUP = /^[0-9a-f]{1,4}$/;
|
||||
|
||||
function isLocalIPv4(address: string) {
|
||||
if (!IPV4_LITERAL.test(address)) {
|
||||
return false;
|
||||
}
|
||||
const octets = address.split('.').map(Number);
|
||||
if (octets.some(octet => octet > 255)) {
|
||||
return false;
|
||||
}
|
||||
const [a, b] = octets;
|
||||
return (
|
||||
a === 127 ||
|
||||
a === 10 ||
|
||||
(a === 172 && b >= 16 && b <= 31) ||
|
||||
(a === 192 && b === 168) ||
|
||||
(a === 169 && b === 254)
|
||||
);
|
||||
}
|
||||
|
||||
function parseIPv6(address: string): number[] | null {
|
||||
const halves = address.split('::');
|
||||
if (halves.length > 2) {
|
||||
return null;
|
||||
}
|
||||
const head = halves[0] ? halves[0].split(':') : [];
|
||||
const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
|
||||
const missing = 8 - head.length - tail.length;
|
||||
if (halves.length === 1 ? missing !== 0 : missing < 1) {
|
||||
return null;
|
||||
}
|
||||
const groups = [
|
||||
...head,
|
||||
...Array.from({ length: halves.length === 2 ? missing : 0 }, () => '0'),
|
||||
...tail,
|
||||
];
|
||||
if (!groups.every(group => IPV6_GROUP.test(group))) {
|
||||
return null;
|
||||
}
|
||||
return groups.map(group => parseInt(group, 16));
|
||||
}
|
||||
|
||||
function isLocalIPv6(address: string) {
|
||||
const groups = parseIPv6(address.replace(/%.*$/, ''));
|
||||
if (!groups) {
|
||||
return false;
|
||||
}
|
||||
const isLoopback = groups.slice(0, 7).every(g => g === 0) && groups[7] === 1;
|
||||
return (
|
||||
isLoopback ||
|
||||
(groups[0] & 0xfe00) === 0xfc00 ||
|
||||
(groups[0] & 0xffc0) === 0xfe80
|
||||
);
|
||||
}
|
||||
|
||||
export function isLocalNetworkHost(host: string) {
|
||||
const name = host
|
||||
.toLowerCase()
|
||||
.replace(/^\[(.*)\]$/, '$1')
|
||||
.replace(/\.$/, '');
|
||||
if (name.includes(':')) {
|
||||
return isLocalIPv6(name);
|
||||
}
|
||||
const labels = name.split('.');
|
||||
if (labels.some(label => label.length === 0)) {
|
||||
return false;
|
||||
}
|
||||
if (IPV4_LIKE_LABEL.test(labels[labels.length - 1])) {
|
||||
return isLocalIPv4(name);
|
||||
}
|
||||
return labels.length === 1 || labels[labels.length - 1] === 'local';
|
||||
}
|
||||
|
||||
export function isBlockedCleartextUrl(url: URL) {
|
||||
return (
|
||||
(url.protocol === 'http:' || url.protocol === 'ws:') &&
|
||||
!isLocalNetworkHost(url.hostname)
|
||||
);
|
||||
}
|
||||
@@ -1547,6 +1547,10 @@ export function useAFFiNEI18N(): {
|
||||
* `Unable to connect to the server.`
|
||||
*/
|
||||
["com.affine.auth.sign.add-selfhosted.error"](): string;
|
||||
/**
|
||||
* `This app only connects to servers on your local network over http. Use an https:// address, or the server's local IP address or .local name.`
|
||||
*/
|
||||
["com.affine.auth.sign.add-selfhosted.public-http"](): string;
|
||||
/**
|
||||
* `Privacy policy`
|
||||
*/
|
||||
|
||||
@@ -369,6 +369,7 @@
|
||||
"com.affine.auth.sign.add-selfhosted.baseurl": "AFFiNE Server URL",
|
||||
"com.affine.auth.sign.add-selfhosted.connect-button": "Connect",
|
||||
"com.affine.auth.sign.add-selfhosted.error": "Unable to connect to the server.",
|
||||
"com.affine.auth.sign.add-selfhosted.public-http": "This app only connects to servers on your local network over http. Use an https:// address, or the server's local IP address or .local name.",
|
||||
"com.affine.auth.sign.add-selfhosted.description": "This is an AFFiNE server hosted by you or your team. After signing in, workspace data is saved to the AFFiNE server you enter, not to AFFiNE Cloud. <1>Learn more about self-hosting.</1>",
|
||||
"com.affine.auth.sign.message": "By clicking “Continue with Google/Email” above, you acknowledge that you agree to AFFiNE's <1>Terms of Conditions</1> and <3>Privacy Policy</3>.",
|
||||
"com.affine.auth.sign.policy": "Privacy policy",
|
||||
|
||||
@@ -341,6 +341,7 @@
|
||||
"com.affine.auth.sign.add-selfhosted.baseurl": "AFFiNE 服务器地址",
|
||||
"com.affine.auth.sign.add-selfhosted.connect-button": "连接",
|
||||
"com.affine.auth.sign.add-selfhosted.error": "无法连接至服务器。",
|
||||
"com.affine.auth.sign.add-selfhosted.public-http": "本应用仅允许通过 http 连接局域网内的服务器。请使用 https:// 地址,或改用服务器的局域网 IP 地址或 .local 名称。",
|
||||
"com.affine.auth.sign.add-selfhosted.description": "这是你或团队自己部署的 AFFiNE。登录后,工作区数据会保存到你填写的 AFFiNE 服务器,而不是 AFFiNE 官方云。<1>了解有关自托管的更多信息。</1>",
|
||||
"com.affine.auth.sign.message": "点击上面的“谷歌登录以继续”,即表示您确认同意 AFFiNE 的<1>条件条款</1>和<3>隐私政策</3>。",
|
||||
"com.affine.auth.sign.policy": "隐私政策",
|
||||
|
||||
Reference in new issue
Block a user