Skip to content

Commit 5396ee2

Browse files
committed
feat(remote-connect): carry the relay service version as a query parameter
The official endpoint moves from a versioned path to a versioned query: `https://remote.openbitfun.com/relay?v=1.0.9`. One proxy location now serves every build, and the bare origin is the account controller, so a release no longer needs its own location and an invitation can be opened without knowing a version path. `/v/1.0.2/` stays live on the same process and database. Both paths are one deployment: a stored token, master key, or device registration from either alias keeps working, and neither is reported as retired. Compatibility is enforced end to end: - product-domains owns the endpoint helpers: base extraction (version, query, fragment removed), version reading, live-alias deployment comparison, and page URLs that keep `?v=` before the fragment. - URL validation accepts exactly one `v=<version>` parameter and rejects every other query, so the query can never carry per-request data. Rust, Kotlin, and ArkTS validators follow the same rule. - Path joins (`join_relay_url`, page URLs, socket paths, RPC payload endpoints) always use the base, never the versioned string. - Pairing links keep the version before the fragment, and both mobile clients accept invitations from either live alias. Published Pages are served from a separate browser origin in deployment: a Page document executes user-authored JavaScript and must not share storage with the controller that holds the device key. The deploy template documents the query endpoint, the bare-origin controller, and the `/p/` redirect. Verified with `cargo test -p openbitfun-product-domains`, `cargo test -p openbitfun-services-integrations --features remote-connect`, mobile-web `test:account-login`, and the web-ui relay endpoint tests.
1 parent 5eecd04 commit 5396ee2

30 files changed

Lines changed: 849 additions & 80 deletions

File tree

‎deploy/relay-v1/README.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,44 @@ WantedBy=timers.target
263263
is cheap: hourly traffic moves past the window in seconds, versus 455 seconds
264264
for the first pass over 2.17 M rows. Pruning and retiring are separate steps —
265265
pruning only buys time until the version reaches the retirement switch above.
266+
267+
## Version-by-query endpoint and the Page origin
268+
269+
Releases used to be separated by a proxy location (`/v/<version>/`). A client
270+
now targets `https://remote.openbitfun.com/relay?v=<service-version>`: the
271+
version travels as a query parameter, one proxy location serves every build,
272+
and the bare origin is the account controller. `/v/1.0.2/` stays live on the
273+
same process and database for builds that predate the parameter, so both
274+
aliases share credentials and device registration.
275+
276+
```nginx
277+
location = /relay { return 308 /relay/; }
278+
location ^~ /relay/ {
279+
proxy_pass http://127.0.0.1:19702/; # strip the prefix
280+
proxy_http_version 1.1;
281+
proxy_set_header Host $host; # bare host: the Relay compares it verbatim
282+
proxy_set_header X-Forwarded-For $remote_addr;
283+
proxy_set_header X-Forwarded-Proto $scheme;
284+
proxy_set_header Upgrade $http_upgrade;
285+
proxy_set_header Connection $connection_upgrade;
286+
proxy_buffering off;
287+
client_max_body_size 65m;
288+
}
289+
location = / { proxy_pass http://127.0.0.1:19702/; } # the controller SPA
290+
location = /index.html { proxy_pass http://127.0.0.1:19702/index.html; }
291+
location ^~ /assets/ { proxy_pass http://127.0.0.1:19702; }
292+
location ^~ /brand/ { proxy_pass http://127.0.0.1:19702; }
293+
location / { return 410; } # keep unversioned paths closed
294+
```
295+
296+
Published Pages must not share a browser origin with the controller: Page
297+
documents execute user-authored JavaScript, and the controller keeps its device
298+
key and Relay credential in that origin's IndexedDB. Serve `/p/` and
299+
`/api/page-auth/` from a separate host (`RELAY_PAGE_PUBLIC_BASE_URL`) and keep
300+
`RELAY_PAGE_AUTH_BASE_URL` on a third origin. Redirect the old path instead of
301+
serving content there:
302+
303+
```nginx
304+
location ^~ /v/1.0.2/p/ { rewrite ^/v/1\.0\.2(/p/.*)$ https://pages.example.com$1 redirect; }
305+
location ^~ /relay/p/ { rewrite ^/relay(/p/.*)$ https://pages.example.com$1 redirect; }
306+
```

‎src/apps/cli/src/account_guidance.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,10 @@ mod tests {
147147

148148
#[test]
149149
fn the_endpoint_variant_prefers_a_retired_official_endpoint() {
150-
let older = DEFAULT_RELAY_URL.replace("/v/1.0.2", "/v/1.0.1");
151-
let retired = account_failure_guidance_for_endpoint("some generic error", &older);
150+
// `/v/1.0.2` and `/relay` are live aliases of one deployment; any other
151+
// `/v/<release>` path belongs to a retired deployment.
152+
let older = "https://remote.openbitfun.com/v/1.0.1";
153+
let retired = account_failure_guidance_for_endpoint("some generic error", older);
152154
assert_eq!(retired.0, UPDATE_SENTENCE);
153155
assert_eq!(retired.1, Some(UPDATE_HINT));
154156

‎src/apps/mobile/harmonyos/entry/src/main/ets/pages/viewmodel/SettingsController.ets‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { GitHubAccountProfile, GitHubProfileLoader } from '../../services/GitHubAccountProfile';
2-
import { normalizeAccountRelayUrl, OFFICIAL_RELAY_URL } from '../../services/AccountDeviceLink';
2+
import { normalizeAccountRelayUrl, OFFICIAL_RELAY_URL, sameRelayDeployment } from '../../services/AccountDeviceLink';
33
import { RemoteI18n } from '../../i18n/RemoteI18n';
44
import { stampRemoteSessionsDevice } from '../../services/RemoteSessionIdentity';
55
import {
@@ -173,7 +173,7 @@ export class SettingsController {
173173
selectAccountRelay(relayUrl: string): void {
174174
const endpoint = normalizeAccountRelayUrl(relayUrl);
175175
if (!endpoint) throw new Error('Invalid Relay URL');
176-
if (this.cloudRelayUrl !== endpoint) {
176+
if (!sameRelayDeployment(this.cloudRelayUrl, endpoint)) {
177177
this.teardownCloudAccountProjection(this.requireCloud());
178178
this.selectedRelayUrl = endpoint;
179179
}
@@ -784,7 +784,8 @@ export class SettingsController {
784784
if (!persisted) {
785785
return;
786786
}
787-
if (/^https:\/\/remote\.openbitfun\.com\/v\/[^/]+\/?$/.test(persisted.relayUrl) && persisted.relayUrl.replace(/\/+$/, '') !== OFFICIAL_RELAY_URL) {
787+
if (/^https:\/\/remote\.openbitfun\.com\/v\/[^/]+\/?$/.test(persisted.relayUrl)
788+
&& !sameRelayDeployment(persisted.relayUrl, OFFICIAL_RELAY_URL)) {
788789
// Relay credentials are database-scoped; never replay an older credential at a new endpoint.
789790
this.selectedRelayUrl = OFFICIAL_RELAY_URL;
790791
this.cloudRelayUrl = OFFICIAL_RELAY_URL;

‎src/apps/mobile/harmonyos/entry/src/main/ets/services/AccountDeviceLink.ets‎

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,57 @@
1-
export const OFFICIAL_RELAY_URL: string = 'https://remote.openbitfun.com/v/1.0.2';
1+
/** Hosted Relay service version announced by the official endpoint. */
2+
export const RELAY_SERVICE_VERSION: string = '1.0.9';
3+
4+
const OFFICIAL_RELAY_ORIGIN: string = 'https://remote.openbitfun.com';
5+
6+
/** Paths served by the same deployed Relay and the same account database.
7+
* `?v=` replaced the path segment as the client-facing version, but `/v/1.0.2`
8+
* stays live for builds that predate the change: a token, master key, or device
9+
* registration obtained through either path is interchangeable, because both
10+
* reach one process and one database. Any other `/v/<version>` path is a
11+
* different deployment. */
12+
const LIVE_RELAY_ENDPOINT_PATHS: string[] = ['/relay', '/v/1.0.2'];
13+
14+
const VERSION_PATTERN: RegExp = /^[A-Za-z0-9.]{1,32}$/;
15+
16+
/** Identity of the official Relay: no version query, no fragment, no trailing
17+
* slash. Every path join and every deployment comparison uses this value. */
18+
export const OFFICIAL_RELAY_URL: string = `${OFFICIAL_RELAY_ORIGIN}/relay`;
19+
20+
/** The same deployment as a user sees and shares it: the service version
21+
* travels as a GET parameter instead of a path segment, so a release no longer
22+
* needs a proxy location of its own. */
23+
export const OFFICIAL_RELAY_ENDPOINT: string = `${OFFICIAL_RELAY_URL}?v=${RELAY_SERVICE_VERSION}`;
24+
225
export interface AccountDeviceLink { relayUrl: string; deviceId: string; }
326

27+
/** Strip the version parameter and any trailing slash, or explain why not.
28+
* Exactly one `v=<version>` parameter is accepted; every other query parameter
29+
* is rejected so the query can never carry per-request data, and a fragment
30+
* means the value is a page rather than an endpoint. */
31+
function endpointBase(value: string): string | undefined {
32+
const text = value.trim();
33+
if (text === '' || text.indexOf('#') >= 0) return undefined;
34+
const mark = text.indexOf('?');
35+
const base = (mark >= 0 ? text.substring(0, mark) : text).replace(/\/+$/, '');
36+
if (mark >= 0) {
37+
const pairs = text.substring(mark + 1).split('&');
38+
if (pairs.length !== 1 || pairs[0].substring(0, 2) !== 'v=' ||
39+
!VERSION_PATTERN.test(pairs[0].substring(2))) return undefined;
40+
}
41+
return base;
42+
}
43+
44+
function officialPath(value: string): string {
45+
return value.startsWith(OFFICIAL_RELAY_ORIGIN) ? value.substring(OFFICIAL_RELAY_ORIGIN.length) : '';
46+
}
47+
448
export function normalizeAccountRelayUrl(value: string): string {
5-
const normalized = value.trim().replace(/\/+$/, '');
6-
if (normalized === OFFICIAL_RELAY_URL) return normalized;
7-
const match = /^(https?:\/\/)(localhost|\[[0-9a-fA-F:]+\]|[0-9.]+)(?::([0-9]{1,5}))?$/.exec(normalized);
49+
const base = endpointBase(value);
50+
if (!base) return '';
51+
// Both live aliases of the official host answer as one deployment, so an
52+
// endpoint stored by an older build still resolves to today's identity.
53+
if (LIVE_RELAY_ENDPOINT_PATHS.indexOf(officialPath(base)) >= 0) return OFFICIAL_RELAY_URL;
54+
const match = /^(https?:\/\/)(localhost|\[[0-9a-fA-F:]+\]|[0-9.]+)(?::([0-9]{1,5}))?$/.exec(base);
855
if (!match) return '';
956
if (match[3] && (Number(match[3]) < 1 || Number(match[3]) > 65535)) return '';
1057
const host = match[2].toLowerCase();
@@ -14,7 +61,33 @@ export function normalizeAccountRelayUrl(value: string): string {
1461
(octets.length === 4 && octets.every((part: number): boolean => Number.isInteger(part) && part >= 0 && part <= 255) &&
1562
(octets[0] === 10 || octets[0] === 127 || (octets[0] === 192 && octets[1] === 168) ||
1663
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) || (octets[0] === 169 && octets[1] === 254)));
17-
return local ? normalized : '';
64+
return local ? base : '';
65+
}
66+
67+
interface RelayEndpointIdentity { origin: string; path: string; }
68+
69+
function endpointIdentity(value: string): RelayEndpointIdentity | undefined {
70+
const base = endpointBase(value);
71+
if (!base) return undefined;
72+
const match = /^(https?):\/\/(\[[0-9a-fA-F:]+\]|[^/?#:@]+)(?::([0-9]{1,5}))?([^?#]*)$/.exec(base);
73+
if (!match) return undefined;
74+
const scheme = match[1].toLowerCase();
75+
const port = match[3] ? Number(match[3]) : (scheme === 'https' ? 443 : 80);
76+
if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined;
77+
return { origin: `${scheme}://${match[2].toLowerCase()}:${port}`, path: match[4] };
78+
}
79+
80+
/** Whether two endpoints resolve to the same deployed Relay.
81+
* This is the comparison behind reusing a stored token or master key: both live
82+
* aliases of one host count as one deployment, so a build that moves from
83+
* `/v/1.0.2` to `/relay?v=` keeps its credential, while any other versioned
84+
* path is a different or retired deployment. */
85+
export function sameRelayDeployment(left: string, right: string): boolean {
86+
const a = endpointIdentity(left);
87+
const b = endpointIdentity(right);
88+
if (!a || !b || a.origin !== b.origin) return false;
89+
return a.path === b.path ||
90+
(LIVE_RELAY_ENDPOINT_PATHS.indexOf(a.path) >= 0 && LIVE_RELAY_ENDPOINT_PATHS.indexOf(b.path) >= 0);
1891
}
1992

2093
/** Endpoint and target are hints; the account directory is the authority. */

‎src/apps/mobile/harmonyos/entry/src/test/TransportAndGeneralChatUnit.test.ets‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import { ReadFileChunkResult } from '../main/ets/model/RemoteModels';
22
import { GitHubAccountProfile, GitHubProfileLoader, normalizeGitHubProfile, readCachedGitHubProfile } from '../main/ets/services/GitHubAccountProfile';
3-
import { accountDeviceLink } from '../main/ets/services/AccountDeviceLink';
3+
import {
4+
accountDeviceLink,
5+
normalizeAccountRelayUrl,
6+
OFFICIAL_RELAY_ENDPOINT,
7+
OFFICIAL_RELAY_URL,
8+
RELAY_SERVICE_VERSION,
9+
sameRelayDeployment
10+
} from '../main/ets/services/AccountDeviceLink';
411
import { describe, it, expect } from '@ohos/hypium';
512
import { RemoteI18n } from '../main/ets/i18n/RemoteI18n';
613
import { ChatSessionController, ChatSessionSnapshot } from '../main/ets/services/ChatSessionController';
@@ -606,18 +613,46 @@ export default function transportAndGeneralChatUnitTest() {
606613
});
607614

608615
it('uses the same device selector for official and LAN endpoints', 0, () => {
609-
for (const endpoint of ['https://remote.openbitfun.com/v/1.0.2', 'http://192.168.1.10:9700']) {
616+
for (const endpoint of [OFFICIAL_RELAY_URL, 'http://192.168.1.10:9700']) {
610617
const parsed = accountDeviceLink(`${endpoint}/#/pair?did=desktop-1`);
611618
expect(parsed?.deviceId).assertEqual('desktop-1');
612619
expect(parsed?.relayUrl).assertEqual(endpoint);
613620
}
614621
});
622+
it('resolves a versioned link to the endpoint base', 0, () => {
623+
// A link the user opens carries the service version as a GET parameter
624+
// before the fragment; the endpoint it resolves to is the base, so no join
625+
// can ever produce `...?v=1.0.9/api/...`.
626+
expect(OFFICIAL_RELAY_ENDPOINT).assertEqual(`${OFFICIAL_RELAY_URL}?v=${RELAY_SERVICE_VERSION}`);
627+
const versioned = accountDeviceLink(`${OFFICIAL_RELAY_ENDPOINT}/#/pair?did=desktop-1`);
628+
expect(versioned?.deviceId).assertEqual('desktop-1');
629+
expect(versioned?.relayUrl).assertEqual(OFFICIAL_RELAY_URL);
630+
expect(normalizeAccountRelayUrl(OFFICIAL_RELAY_ENDPOINT)).assertEqual(OFFICIAL_RELAY_URL);
631+
// Exactly one `v` may ride along: every other parameter is not an endpoint.
632+
expect(normalizeAccountRelayUrl(`${OFFICIAL_RELAY_URL}?v=1.0.9&relay=evil`)).assertEqual('');
633+
expect(normalizeAccountRelayUrl(`${OFFICIAL_RELAY_URL}?version=1.0.9`)).assertEqual('');
634+
expect(normalizeAccountRelayUrl(`${OFFICIAL_RELAY_URL}?v=1.0.9#/pair?did=desktop-1`)).assertEqual('');
635+
});
636+
it('keeps the older official path interchangeable with the current one', 0, () => {
637+
const legacy = accountDeviceLink('https://remote.openbitfun.com/v/1.0.2/#/pair?did=desktop-1');
638+
expect(legacy?.deviceId).assertEqual('desktop-1');
639+
expect(legacy?.relayUrl).assertEqual(OFFICIAL_RELAY_URL);
640+
// Both paths reach one process and one account database, so a stored token
641+
// or master key from either stays usable.
642+
expect(sameRelayDeployment('https://remote.openbitfun.com/v/1.0.2', OFFICIAL_RELAY_URL)).assertTrue();
643+
expect(sameRelayDeployment(OFFICIAL_RELAY_ENDPOINT, OFFICIAL_RELAY_URL)).assertTrue();
644+
expect(sameRelayDeployment('https://remote.openbitfun.com/v/1.0.0', OFFICIAL_RELAY_URL)).assertFalse();
645+
expect(sameRelayDeployment('https://remote.openbitfun.com/v/1.0.0', 'https://remote.openbitfun.com/v/1.0.2')).assertFalse();
646+
expect(sameRelayDeployment('http://remote.openbitfun.com/relay', OFFICIAL_RELAY_URL)).assertFalse();
647+
expect(sameRelayDeployment('http://192.168.1.10:9700/', 'http://192.168.1.10:9700')).assertTrue();
648+
});
615649
it('rejects credentials, legacy rooms, duplicate targets and public lookalikes', 0, () => {
616-
const prefix = 'https://remote.openbitfun.com/v/1.0.2/#/pair?';
650+
const prefix = `${OFFICIAL_RELAY_ENDPOINT}/#/pair?`;
617651
for (const suffix of ['did=desktop-1&pk=untrusted', 'did=desktop-1&relay=evil',
618652
'did=desktop-1&did=desktop-2', 'did=%00', 'did=%ZZ', 'room=old&pk=old']) {
619653
expect(accountDeviceLink(prefix + suffix)).assertUndefined();
620654
}
655+
expect(accountDeviceLink('https://evil.test/relay/#/pair?did=desktop-1')).assertUndefined();
621656
expect(accountDeviceLink('https://evil.test/v/1.0.0/#/pair?did=desktop-1')).assertUndefined();
622657
expect(accountDeviceLink('https://remote.openbitfun.com@evil.test/v/1.0.0/#/pair?did=desktop-1')).assertUndefined();
623658
});
@@ -656,7 +691,9 @@ export default function transportAndGeneralChatUnitTest() {
656691
describe('RemoteSessionManager account connection', () => {
657692
it('loads account device sessions through either relay endpoint', 0, async () => {
658693
const manager = new RemoteSessionManager();
659-
for (const endpoint of ['https://remote.openbitfun.com/v/1.0.2', 'http://192.168.1.10:9700']) {
694+
// The versioned official endpoint and the older live path both address the
695+
// one deployment, next to a LAN relay that never carries a version.
696+
for (const endpoint of [OFFICIAL_RELAY_ENDPOINT, 'https://remote.openbitfun.com/v/1.0.2', 'http://192.168.1.10:9700']) {
660697
const result = await manager.connectAccountDevice(new RecordingAccountDeviceClient(), endpoint,
661698
{ token: 'token', userId: 'account-user', masterKey: new Uint8Array(32) }, 'desktop-device');
662699
expect(result.workspace.path).assertEqual('/account-workspace');

‎src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountDeviceLink.kt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.openbitfun.mobile.core.feature.account
22

33
import com.openbitfun.mobile.core.transport.accountDeviceLink
4+
import com.openbitfun.mobile.core.transport.sameRelayDeployment
45

56
public enum class AccountDeviceLinkStatus { INVALID, SIGN_IN_REQUIRED, UNAVAILABLE, READY }
67

@@ -13,7 +14,7 @@ public fun resolveAccountDeviceLink(url: String, state: AccountUiState): Account
1314
val link = accountDeviceLink(url)
1415
?: return AccountDeviceLinkResult(AccountDeviceLinkStatus.INVALID, null)
1516
val id = link.deviceId
16-
val ready = (state as? AccountUiState.Ready)?.takeIf { it.relayUrl == link.relayUrl }
17+
val ready = (state as? AccountUiState.Ready)?.takeIf { sameRelayDeployment(it.relayUrl, link.relayUrl) }
1718
?: return AccountDeviceLinkResult(AccountDeviceLinkStatus.SIGN_IN_REQUIRED, id, link.relayUrl)
1819
// A scanned target must never resolve to a device the Relay confirmed is
1920
// incompatible; the link reads as unavailable, the same as offline.

‎src/apps/mobile/shared/core-feature/src/commonMain/kotlin/com/openbitfun/mobile/core/feature/account/AccountStore.kt‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -254,20 +254,32 @@ public class AccountStore internal constructor(
254254
)
255255
return@launch
256256
}
257-
if (restored.relayUrl.trimEnd('/').startsWith("https://remote.openbitfun.com/v/") &&
258-
restored.relayUrl.trimEnd('/') != AccountDefaults.CLOUD_RELAY_URL) {
259-
// Relay tokens belong to their issuing database. Keep the old encrypted
260-
// record/cache, but require a fresh login before using the new endpoint.
261-
selectedRelayUrl = AccountDefaults.CLOUD_RELAY_URL
257+
val storedRelay = restored.relayUrl.trimEnd('/')
258+
val currentRelay = AccountDefaults.CLOUD_RELAY_URL
259+
// Relay tokens belong to their issuing database. `/relay` and the older
260+
// `/v/1.0.2` are live aliases of one deployment and one database, so a
261+
// credential saved against either keeps working; only some other
262+
// versioned path means a relay this build must sign in against again.
263+
if (storedRelay.startsWith("https://remote.openbitfun.com/v/") &&
264+
!com.openbitfun.mobile.core.transport.sameRelayDeployment(storedRelay, currentRelay)) {
265+
// Keep the old encrypted record/cache, but require a fresh login
266+
// before using the new endpoint.
267+
selectedRelayUrl = currentRelay
262268
expireSession(AccountFailureReason.AUTHENTICATION, AccountFailureStage.AUTHENTICATION)
263269
return@launch
264270
}
265-
session = restored
266-
selectedRelayUrl = restored.relayUrl
271+
// Store today's endpoint identity: a session saved against a live alias
272+
// or against the versioned official endpoint is joined and compared on
273+
// the bare base, so the query can never reach a path.
274+
val current = if (com.openbitfun.mobile.core.transport.sameRelayDeployment(storedRelay, currentRelay)) {
275+
restored.copy(relayUrl = currentRelay)
276+
} else restored
277+
session = current
278+
selectedRelayUrl = current.relayUrl
267279
// Local credential restoration and remote directory availability are
268280
// separate facts. Publish identity before any network wait, but grant
269281
// no target authority until an authenticated membership snapshot arrives.
270-
publishReady(restored, emptyList(), selectionConfirmed = false)
282+
publishReady(current, emptyList(), selectionConfirmed = false)
271283
refreshDevices()
272284
}
273285
}

0 commit comments

Comments
 (0)