Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions deps/cloudxr/webxr_client/helpers/oobControlToken.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @jest-environment jsdom
*/

type TokenModule = typeof import('./oobControlToken');

let captureOobControlToken: TokenModule['captureOobControlToken'];
let getOobControlToken: TokenModule['getOobControlToken'];

const HUB = 'oobEnable=1&serverIP=10.0.0.5&port=48322';

function visit(url: string): void {
window.history.replaceState({ keep: 'me' }, '', url);
}

function hubQuery(): URLSearchParams {
return new URLSearchParams(HUB);
}

// Fresh module per test: the in-memory fallback map is module state.
beforeEach(async () => {
window.sessionStorage.clear();
jest.resetModules();
({ captureOobControlToken, getOobControlToken } = await import('./oobControlToken'));
});

describe('captureOobControlToken', () => {
it('lifts a fragment token, strips it, and keeps the route and history state', () => {
visit(`/client/?${HUB}#/real/dexmate?controlToken=abc-123_XYZ`);
captureOobControlToken();
expect(window.location.hash).toBe('#/real/dexmate');
expect(window.location.search).toBe(`?${HUB}`);
expect(window.history.state).toEqual({ keep: 'me' });
expect(getOobControlToken(hubQuery())).toBe('abc-123_XYZ');
});

it('handles a fragment with no route', () => {
visit(`/client/?${HUB}#?controlToken=tok`);
captureOobControlToken();
expect(window.location.hash).toBe('');
expect(getOobControlToken(hubQuery())).toBe('tok');
});

it('round-trips a URL-encoded token', () => {
visit(`/client/?${HUB}#/real?controlToken=${encodeURIComponent('a&b=c?d#e')}`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('a&b=c?d#e');
});

it('reads a legacy query token and strips it, keeping other params', () => {
visit(`/client/?${HUB}&controlToken=legacy#/real`);
captureOobControlToken();
expect(window.location.search).toBe(`?${HUB}`);
expect(window.location.hash).toBe('#/real');
expect(getOobControlToken(hubQuery())).toBe('legacy');
});

it('prefers the fragment token when both are present', () => {
visit(`/client/?${HUB}&controlToken=old#/real?controlToken=new`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('new');
expect(window.location.search).not.toContain('controlToken');
expect(window.location.hash).toBe('#/real');
});

it('keeps the stored token across a reload that carries none', () => {
visit(`/client/?${HUB}#/real?controlToken=tok`);
captureOobControlToken();
visit(`/client/?${HUB}#/real`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('tok');
});

it('replaces a stale stored token with a newly supplied one', () => {
visit(`/client/?${HUB}#/real?controlToken=stale`);
captureOobControlToken();
visit(`/client/?${HUB}#/real?controlToken=fresh`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('fresh');
});

it('does not reuse one hub endpoint token for another', () => {
visit(`/client/?${HUB}#/real?controlToken=tok`);
captureOobControlToken();
expect(getOobControlToken(new URLSearchParams('serverIP=10.0.0.6&port=48322'))).toBeUndefined();
expect(getOobControlToken(new URLSearchParams('serverIP=10.0.0.5&port=49000'))).toBeUndefined();
});

it('leaves the URL alone when there is no token', () => {
visit(`/client/?${HUB}#/real`);
captureOobControlToken();
expect(window.location.href).toContain(`?${HUB}#/real`);
expect(getOobControlToken(hubQuery())).toBeUndefined();
});

it('prefers the fresh in-memory token over a stale stored one when the write is denied', () => {
window.sessionStorage.setItem('oobControlToken:10.0.0.5:48322', 'stale');
const spy = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('quota');
});
const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
visit(`/client/?${HUB}#/real?controlToken=fresh`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('fresh');
spy.mockRestore();
warn.mockRestore();
});

it('still serves the token for this page load when sessionStorage is denied', () => {
const spy = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('denied');
});
const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
visit(`/client/?${HUB}#/real?controlToken=memonly`);
captureOobControlToken();
expect(getOobControlToken(hubQuery())).toBe('memonly');
expect(warn).toHaveBeenCalled();
spy.mockRestore();
warn.mockRestore();
});
});
101 changes: 101 additions & 0 deletions deps/cloudxr/webxr_client/helpers/oobControlToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* OOB control token delivery.
*
* The host puts the token in the URL fragment (`#/route?controlToken=…`) so it is
* never sent in an HTTP request target or Referer. The page lifts it into
* sessionStorage (tab-scoped, keyed by hub endpoint so a reload keeps auth) and
* strips it from the address bar. A `?controlToken=` query is still read for
* hand-built bookmarks, but that URL has already been sent over the network.
*/

const PARAM = 'controlToken';
const STORAGE_PREFIX = 'oobControlToken:';

// Fallback when sessionStorage is denied: survives this page load only.
const memoryTokens = new Map<string, string>();

function endpointKey(search: URLSearchParams): string {
const host = (search.get('serverIP') ?? '').trim();
const port = (search.get('port') ?? '').trim();
return `${STORAGE_PREFIX}${host}:${port}`;
}

function storeToken(key: string, token: string): void {
memoryTokens.set(key, token);
try {
window.sessionStorage.setItem(key, token);
} catch {
console.warn(
'[Teleop] sessionStorage unavailable; OOB control token will not survive a reload'
);
}
}

function loadToken(key: string): string | null {
// This page load's token wins: a denied write must not fall back to an older stored one.
const current = memoryTokens.get(key);
if (current) return current;
try {
return window.sessionStorage.getItem(key) || null;
} catch {
return null;
}
}

/**
* Lifts a control token out of the URL (fragment first, then legacy query) into
* session storage and removes it from the address bar. Call before anything
* rewrites or reads the fragment. A supplied token replaces any stored one;
* with none supplied the stored token for this endpoint is kept.
*/
export function captureOobControlToken(): void {
const { pathname, search, hash } = window.location;
const searchParams = new URLSearchParams(search);

// Fragment layout: `#<route>?<params>`; split at the first '?'.
const fragment = hash.replace(/^#/, '');
const split = fragment.indexOf('?');
const route = split === -1 ? fragment : fragment.slice(0, split);
const fragmentParams = new URLSearchParams(split === -1 ? '' : fragment.slice(split + 1));

const token = fragmentParams.get(PARAM) || searchParams.get(PARAM);
if (!searchParams.has(PARAM) && !fragmentParams.has(PARAM)) return;

if (token) storeToken(endpointKey(searchParams), token);

searchParams.delete(PARAM);
fragmentParams.delete(PARAM);
const newSearch = searchParams.toString();
const newFragmentParams = fragmentParams.toString();
const newHash =
route || newFragmentParams
? `#${route}${newFragmentParams ? `?${newFragmentParams}` : ''}`
: '';
window.history.replaceState(
window.history.state,
'',
`${pathname}${newSearch ? `?${newSearch}` : ''}${newHash}`
);
}

/** Control token for the hub named by the current `serverIP`/`port` query, if any. */
export function getOobControlToken(search: URLSearchParams): string | undefined {
return loadToken(endpointKey(search)) ?? undefined;
}
3 changes: 2 additions & 1 deletion deps/cloudxr/webxr_client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type {
NetworkMetricsUpdate,
RenderMetricsUpdate,
} from '@helpers/metricsUpdates';
import { getOobControlToken } from '@helpers/oobControlToken';
import { overridePressureObserver } from '@helpers/overridePressureObserver';
import { kPerformanceOptions } from '@helpers/PerformanceProfiles';
import CloudXRComponent from '@helpers/react/CloudXRComponent';
Expand Down Expand Up @@ -1002,7 +1003,7 @@ function AppContent() {
let previousPresenceMessage: string | undefined;
const channel = new HeadsetControlChannel({
url: hubWsUrl,
token: readUrlParam(p, 'controlToken') ?? undefined,
token: getOobControlToken(p),
onPresenceRecovery: state => {
const messages: Record<string, string> = {
paused: 'Headset paused',
Expand Down
5 changes: 5 additions & 0 deletions deps/cloudxr/webxr_client/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@
import React from 'react';
import ReactDOM from 'react-dom/client';

import { captureOobControlToken } from '@helpers/oobControlToken';

import App from './App';
import { mountBuildInfoOverlayIfRequested } from './BuildInfoOverlay';

// Start the React app immediately in the 3d-ui container
function startApp() {
// Before React: App canonicalizes the URL fragment on mount.
captureOobControlToken();

const reactContainer = document.getElementById('3d-ui');

if (reactContainer) {
Expand Down
108 changes: 108 additions & 0 deletions deps/cloudxr/webxr_client/tests/playwright/OobControlTokenTest.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/

// @ts-check
const { spawn } = require('child_process');
const path = require('path');
const { createInterface } = require('readline');
const { test, expect } = require('@playwright/test');

/**
* The real App.tsx (app-mock build, :8082) delivering the OOB control token to a real
* OOBControlHub (tests/python/core/cloudxr/oob_hub_test_server.py): token in the URL fragment ->
* authenticated register -> token stripped from the URL -> reload -> authenticated register again.
* The hub speaks plain ws:// on loopback while the app dials wss://, so the page's WebSocket is
* bridged to the hub with page.routeWebSocket. Does not cover adb launch or a real CloudXR stream.
*/

const HUB_SCRIPT = path.resolve(
__dirname,
'../../../../../tests/python/core/cloudxr/oob_hub_test_server.py'
);
// Must match TEST_CONTROL_TOKEN in oob_hub_test_server.py.
const HUB_TOKEN = 'oob-hub-test-token';
const ROUTE = 'sim/isaaclab';
const HUB_QUERY = 'oobEnable=1&serverIP=127.0.0.1&port=48322';

/** Starts the hub; `connectedCount()` is how many snapshots so far showed a connected headset. */
async function startHub() {
const proc = spawn('python3', [HUB_SCRIPT], { stdio: ['ignore', 'pipe', 'pipe'] });
let connected = 0;
const port = await new Promise((resolve, reject) => {
proc.once('error', reject);
proc.once('exit', code => reject(new Error(`hub exited early (${code})`)));
createInterface({ input: proc.stdout }).on('line', line => {
const ready = /^READY (\d+)$/.exec(line);
if (ready) resolve(Number(ready[1]));
if (
line.startsWith('SNAPSHOT ') &&
JSON.parse(line.slice(9)).headsets.some(h => h.connected)
) {
connected += 1;
}
});
});
return { proc, port, connectedCount: () => connected };
}

/** Bridges the page's wss://…/oob/v1/ws to the plain-ws hub. */
async function bridgeHub(page, hubPort) {
await page.routeWebSocket(/\/oob\/v1\/ws/, ws => {
const upstream = new WebSocket(`ws://127.0.0.1:${hubPort}`);
const queued = [];
upstream.onopen = () => queued.splice(0).forEach(m => upstream.send(m));
upstream.onmessage = event => ws.send(event.data);
upstream.onclose = () => ws.close();
ws.onMessage(message =>
upstream.readyState === 1 ? upstream.send(message) : queued.push(message)
);
ws.onClose(() => upstream.close());
});
}

let hub;
test.beforeEach(async () => {
hub = await startHub();
});
test.afterEach(() => {
hub?.proc.kill('SIGKILL');
});

test('fragment token authenticates with the hub, is stripped, and survives a reload', async ({
page,
}) => {
const requests = [];
page.on('request', request =>
requests.push(`${request.url()} ${request.headers().referer ?? ''}`)
);
await bridgeHub(page, hub.port);

await page.goto(`http://localhost:8082/?${HUB_QUERY}#/${ROUTE}?controlToken=${HUB_TOKEN}`);
await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(1);

const afterLoad = new URL(page.url());
expect(afterLoad.hash).toBe(`#/${ROUTE}`);
expect(afterLoad.search).toBe(`?${HUB_QUERY}`);

await page.reload();
await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(2);
expect(new URL(page.url()).hash).toBe(`#/${ROUTE}`);

expect(requests.filter(r => r.includes(HUB_TOKEN))).toEqual([]);
});

test('a legacy query token authenticates and is stripped', async ({ page }) => {
await bridgeHub(page, hub.port);
await page.goto(`http://localhost:8082/?${HUB_QUERY}&controlToken=${HUB_TOKEN}#/${ROUTE}`);
await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(1);
expect(page.url()).not.toContain('controlToken');
});

test('without a token the hub rejects the headset', async ({ page }) => {
await bridgeHub(page, hub.port);
await page.goto(`http://localhost:8082/?${HUB_QUERY}#/${ROUTE}`);
await page.waitForTimeout(5000);
expect(hub.connectedCount()).toBe(0);
});
Loading
Loading