Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f042b49
Support token files for direct desktop remote connections
francoisnt Oct 24, 2026
e801a6e
Merge remote-tracking branch 'upstream/main' into feature/remote-toke…
francoisnt Oct 24, 2026
8142f05
Merge remote-tracking branch 'upstream/main' into feature/remote-toke…
francoisnt Nov 14, 2026
a0e76a1
test: preserve resolved connection token during ordinary reconnection
sunny-kavixo Nov 15, 2026
1da657f
Merge remote-tracking branch 'upstream/main' into feature/remote-toke…
francoisnt Nov 19, 2026
8a4ba46
Merge pull request #1 from sunny-kavixo/test/remote-token-file-reconn…
francoisnt Nov 19, 2026
7d00b58
Merge remote-tracking branch 'origin/feature/remote-token-file' into …
francoisnt Nov 20, 2026
aa2c901
Clarify remote token file behavior on reconnect
francoisnt Nov 20, 2026
f3ad299
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 20, 2026
13c0ba4
Preserve the direct remote token across reconnects
francoisnt Nov 20, 2026
dad7e3e
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 20, 2026
cbff2c5
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 20, 2026
c0c1b06
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 20, 2026
118aa50
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 21, 2026
cad58b6
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 23, 2026
0b700ff
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 23, 2026
ae3b64a
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 24, 2026
e5a9033
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 24, 2026
c030a83
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 24, 2026
79b8ed1
Merge upstream/main into feature/remote-token-file
francoisnt Nov 30, 2026
6f4e3a0
Merge branch 'main' into feature/remote-token-file
francoisnt Nov 30, 2026
662ee45
Merge upstream/main into feature/remote-token-file
francoisnt Nov 30, 2026
f6cc04f
Merge branch 'main' into feature/remote-token-file
francoisnt Dec 1, 2026
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
12 changes: 8 additions & 4 deletions src/vs/code/electron-main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import '../../platform/update/common/update.config.contribution.js';

import { app, dialog } from 'electron';
import { RemoteConnectionTokenError } from '../../platform/remote/node/remoteConnectionToken.js';
import { unlinkSync, promises } from 'fs';
import { URI } from '../../base/common/uri.js';
import { coalesce, distinct } from '../../base/common/arrays.js';
Expand Down Expand Up @@ -92,12 +93,15 @@ import { LINUX_SYSTEM_POLICY_FILE_PATH } from '../../base/common/policy.js';
class CodeMain {

main(): void {
try {
this.startup();
} catch (error) {
this.startup().catch(async error => {
if (!(error instanceof RemoteConnectionTokenError)) {
throw error;
}
console.error(error.message);
await app.whenReady();
dialog.showErrorBox(product.nameLong, error.message);
app.exit(1);
}
});
}

private async startup(): Promise<void> {
Expand Down
7 changes: 7 additions & 0 deletions src/vs/code/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { combineUriFlags } from './cliArgs.js';
import { getStdinFilePath, hasStdinWithoutTty, readFromStdin, stdinDataListener } from '../../platform/environment/node/stdin.js';
import { createWaitMarkerFileSync } from '../../platform/environment/node/wait.js';
import product from '../../platform/product/common/product.js';
import { RemoteConnectionTokenFile, RemoteConnectionTokenError } from '../../platform/remote/node/remoteConnectionToken.js';
import { CancellationTokenSource } from '../../base/common/cancellation.js';
import { isUNC, randomPath } from '../../base/common/extpath.js';
import { Utils } from '../../platform/profiling/common/profiling.js';
Expand All @@ -46,7 +47,13 @@ export async function main(argv: string[]): Promise<void> {

try {
args = parseCLIProcessArgv(argv);
if (!args.help && !args.version) {
await RemoteConnectionTokenFile.read(args);
}
} catch (err) {
if (err instanceof RemoteConnectionTokenError) {
throw err;
}
console.error(err.message);
return;
}
Expand Down
1 change: 1 addition & 0 deletions src/vs/platform/environment/common/argv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export interface NativeParsedArgs {
'enable-smoke-test-driver'?: boolean;
'skip-sessions-welcome'?: boolean;
'remote'?: string;
'remote-token-file'?: string;
'force'?: boolean;
'do-not-sync'?: boolean;
'preserve-env'?: boolean;
Expand Down
1 change: 1 addition & 0 deletions src/vs/platform/environment/node/argv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ export const OPTIONS: OptionDescriptions<Required<NativeParsedArgs>> = {
'telemetry': { type: 'boolean', cat: 't', description: localize('telemetry', "Shows all telemetry events which VS code collects.") },

'remote': { type: 'string', allowEmptyValue: true },
'remote-token-file': { type: 'string', allowEmptyValue: true, cat: 'o', args: 'path', description: localize('remoteConnectionTokenFile', "Read the authentication token for a direct --remote host:port connection from an absolute local file path.") },
'folder-uri': { type: 'string[]', cat: 'o', args: 'uri' },
'file-uri': { type: 'string[]', cat: 'o', args: 'uri' },

Expand Down
32 changes: 32 additions & 0 deletions src/vs/platform/environment/node/argvHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { dirname, resolve } from '../../../base/common/path.js';
import { IProcessEnvironment, isWindows } from '../../../base/common/platform.js';
import { localize } from '../../../nls.js';
import { NativeParsedArgs } from '../common/argv.js';
import { validateRemoteConnectionTokenArguments } from '../../remote/node/remoteConnectionToken.js';
import { ErrorReporter, NATIVE_CLI_COMMANDS, OPTIONS, parseArgs } from './argv.js';

function parseAndValidate(cmdLineArgs: string[], reportWarnings: boolean): NativeParsedArgs {
Expand Down Expand Up @@ -46,6 +47,7 @@ function parseAndValidate(cmdLineArgs: string[], reportWarnings: boolean): Nativ
args._.forEach(arg => assert(/^(\w:)?[^:]+(:\d*){0,2}:?$/.test(arg), localize('gotoValidation', "Arguments in `--goto` mode should be in the format of `FILE(:LINE(:CHARACTER))`.")));
}

validateRemoteConnectionTokenArguments(args);
return args;
}

Expand Down Expand Up @@ -116,3 +118,33 @@ export function addArg(argv: string[], ...args: string[]): string[] {
export function isLaunchedFromCli(env: IProcessEnvironment): boolean {
return env['VSCODE_CLI'] === '1';
}

/** On relaunch, restore the session rather than replaying a launcher's transient remote target. */
export function stripRemoteConnectionTokenLaunchArgs(argv: string[], isDevelopment: boolean): string[] {
const appIndex = isDevelopment ? argv.findIndex(arg => !arg.startsWith('-')) : -1;
const launchArgs = argv.filter((_arg, index) => index !== appIndex);
// Parse once with the same option definitions as the CLI. Never infer whether an
// unknown Chromium switch consumes the remote path that follows it.
const endOfOptions = launchArgs.indexOf('--');
const parsed = parseArgs(endOfOptions === -1 ? launchArgs : launchArgs.slice(0, endOfOptions), OPTIONS);
if (parsed['remote-token-file'] === undefined) {
return argv;
}

const result = appIndex === -1 ? [] : [argv[appIndex]];
const launchOptions = new Set(['_', 'remote', 'remote-token-file', 'new-window', 'reuse-window', 'wait', 'waitMarkerFilePath', 'diff', 'merge', 'goto', 'profile', 'profile-temp']);
for (const key of Object.keys(OPTIONS) as (keyof NativeParsedArgs)[]) {
if (launchOptions.has(key)) {
continue;
}
const value = parsed[key];
if (typeof value === 'string') {
result.push(`--${key}=${value}`);
} else if (value === true) {
result.push(`--${key}`);
} else if (Array.isArray(value)) {
result.push(...value.map(value => `--${key}=${value}`));
}
}
return result;
}
53 changes: 52 additions & 1 deletion src/vs/platform/environment/test/node/argv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import assert from 'assert';
import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js';
import { formatOptions, Option, OptionDescriptions, Subcommand, parseArgs, ErrorReporter } from '../../node/argv.js';
import { addArg } from '../../node/argvHelper.js';
import { addArg, stripRemoteConnectionTokenLaunchArgs } from '../../node/argvHelper.js';

function o(description: string, type: 'boolean' | 'string' | 'string[]' = 'string'): Option<any> {
return {
Expand Down Expand Up @@ -220,3 +220,54 @@ suite('parseArgs', () => {

ensureNoDisposablesAreLeakedInTestSuite();
});


suite('Remote token relaunch arguments', () => {
ensureNoDisposablesAreLeakedInTestSuite();

test('unrelated launches are unchanged', () => {
const args = ['--remote', 'ssh-remote+host', '-r', '/project'];
assert.strictEqual(stripRemoteConnectionTokenLaunchArgs(args, false), args);
});

test('drops transient target and window flags, retaining application options and their values', () => {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'--user-data-dir', '/profile', '--remote', 'localhost:8000', '--remote-token-file', '/token',
'-r', '-w', '--waitMarkerFilePath', '/wait', '--log', 'trace', '/remote/project', '--locale=fr'
], false), ['--locale=fr', '--user-data-dir=/profile', '--log=trace']);
});

test('handles equals syntax and end of options without converting remote paths to local paths', () => {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'--remote=localhost:8000', '--remote-token-file=/token', '--profile', 'Work', '--locale=fr', '--', '-remote-path'
], false), ['--locale=fr']);
});

test('removes grouped short window flags', () => {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'-nr', '--remote=localhost:8000', '--remote-token-file=/token', '/project'
], false), []);
});

test('does not retain remote paths consumed by unknown Chromium switches', () => {
for (const option of ['--some-chromium-switch', '--some-chromium-switch=value']) {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'--remote', '127.0.0.1:9000', '--remote-token-file', '/t', option, '/remote/project'
], false), []);
}
});

test('preserves declared Chromium switches and repeated option values', () => {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'--remote=localhost:8000', '--remote-token-file=/token', '--no-sandbox',
'--proxy-server=http://localhost:8080', '--disable-extension=a', '--disable-extension=b',
'--', '--disable-gpu'
], false), ['--disable-extension=a', '--disable-extension=b', '--no-sandbox', '--proxy-server=http://localhost:8080']);
});

test('preserves the development application path', () => {
assert.deepStrictEqual(stripRemoteConnectionTokenLaunchArgs([
'.', '--remote', 'localhost:8000', '--remote-token-file', '/token', '/remote/project', '--verbose'
], true), ['.', '--verbose']);
});
});
7 changes: 4 additions & 3 deletions src/vs/platform/launch/electron-main/launchMainService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,11 +181,12 @@ export class LaunchMainService implements ILaunchMainService {
}
}

// Open new Window
if (openNewWindow) {
// Token-bearing launches must load the target, even when an existing window can be reused.
if (openNewWindow || args['remote-token-file'] !== undefined) {
usedWindows = await this.windowsMainService.open({
...baseConfig,
forceNewWindow: true,
forceNewWindow: openNewWindow || !args['reuse-window'],
forceReuseWindow: openNewWindow ? undefined : args['reuse-window'],
forceEmpty: true
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Disposable, DisposableStore } from '../../../base/common/lifecycle.js';
import { isMacintosh, isWindows } from '../../../base/common/platform.js';
import { cwd } from '../../../base/common/process.js';
import { assertReturnsDefined } from '../../../base/common/types.js';
import { stripRemoteConnectionTokenLaunchArgs } from '../../environment/node/argvHelper.js';
import { NativeParsedArgs } from '../../environment/common/argv.js';
import { createDecorator } from '../../instantiation/common/instantiation.js';
import { ILogService } from '../../log/common/log.js';
Expand Down Expand Up @@ -681,7 +682,8 @@ export class LifecycleMainService extends Disposable implements ILifecycleMainSe
async relaunch(options?: IRelaunchOptions): Promise<void> {
this.trace('Lifecycle#relaunch()');

const args = process.argv.slice(1);
const originalArgs = process.argv.slice(1);
const args = stripRemoteConnectionTokenLaunchArgs(originalArgs, !this.environmentMainService.isBuilt);
if (options?.addArgs) {
args.push(...options.addArgs);
}
Expand All @@ -696,7 +698,8 @@ export class LifecycleMainService extends Disposable implements ILifecycleMainSe
}

const quitListener = () => {
if (!this.relaunchHandler?.handleRelaunch(options)) {
// Update handlers cannot honor rewritten launch arguments.
if (args !== originalArgs || !this.relaunchHandler?.handleRelaunch(options)) {
this.trace('Lifecycle#relaunch() - calling app.relaunch()');
electron.app.relaunch({ args });
}
Expand Down
2 changes: 2 additions & 0 deletions src/vs/platform/native/common/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,8 @@ export interface ICommonNativeHostService {
startTracing(categories: string, options?: IStartTracingOptions): Promise<void>;

// Connectivity
/** Returns only the calling window's credential for its current remote address. */
getRemoteConnectionToken(authority: string): Promise<string | undefined>;
resolveProxy(url: string): Promise<string | undefined>;
resolveProxyWithPackage(url: string): Promise<IOSProxy[]>;
readProxyConfigWithPackage(): Promise<IOSProxyConfig>;
Expand Down
7 changes: 7 additions & 0 deletions src/vs/platform/native/electron-main/nativeHostMainService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,13 @@ export class NativeHostMainService extends Disposable implements INativeHostMain

//#region Connectivity

async getRemoteConnectionToken(windowId: number | undefined, authority: string): Promise<string | undefined> {
if (windowId === undefined) {
throw new Error(localize('remoteTokenWindow', "A remote connection token requires a window."));
}
return this.windowsMainService.getRemoteConnectionToken(windowId, authority);
}

async resolveProxy(windowId: number | undefined, url: string): Promise<string | undefined> {
const window = this.codeWindowById(windowId);
const session = window?.win?.webContents?.session;
Expand Down
41 changes: 41 additions & 0 deletions src/vs/platform/remote/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!--
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
-->

# Direct desktop remote connections

External launchers can connect the desktop editor to a compatible VS Code server without a resolver extension:

```sh
code --remote 127.0.0.1:PORT --remote-token-file /absolute/path/to/token /remote/project
```

The launcher owns server installation and version matching, server authentication, transport security (for example, an SSH tunnel), and the local token file. Configure the server to require the same token. Protect the local file from other users. VS Code neither creates nor deletes it.

The option requires an absolute local file path and a direct `host:port` authority, including bracketed IPv6 addresses. The token must be non-empty and contain only `0-9`, `a-z`, `A-Z`, `_`, or `-`, with at most one trailing LF or CRLF, matching the server's token-file format. Spaces, a byte-order mark, additional lines, and an empty file are rejected. Missing, unreadable, or invalid files fail the CLI’s initial validation or, when encountered during authority resolution, produce a connection error in the target window. VS Code does not retry without authentication.

Resolver-extension authorities (such as `ssh-remote+host`), URI arguments, add/remove-folder operations, extension development, chat, and command-line-only operations cannot be combined with this option. Existing non-loopback host confirmation and remote-host security checks still apply. Authentication does not encrypt the direct connection; the launcher must provide any required secure transport.

## Credential lifetime

The CLI validates the file locally. When a launch is forwarded to a running editor process, only the file path is forwarded. The target window reads and validates the file during authority resolution. Keep the protected file available for initial authority resolution and any window reloads. A late read failure is reported as a connection error in the target window; it does not abort application startup or close unrelated windows. The normal detached CLI exit does not acknowledge that the window has connected.

The main process retains the file path in memory, scoped to the target window and remote authority (using the same case-insensitive authority comparison as window lookup). It reads the current token during authority resolution, including on window reload. Ordinary network reconnections reuse the resolved token for the session. Reopening a target with the same file path does not force a reload if no file-resolution failure was recorded. A different file path, a missing binding, or recovery from a file-resolution failure loads the target again, subject to the usual unload veto. Replacing the contents of the file takes effect the next time the authority is resolved, such as on window reload. After repairing a server authentication failure, reload the window to retry. Reusing the window for a different remote destination or a local workspace drops the credential. Other windows do not inherit it. A token-bearing launch opens only its requested targets; it does not also restore unrelated session windows. Without a project path it opens a new empty remote window unless `--reuse-window` is explicitly requested.

Session state stores only a non-secret indication that a window requires a token. After exiting and starting without the option, such a restored window refuses to connect and asks for another launch with the token file. Reusing that address and workspace for a server without authentication does not automatically clear this requirement; an explicit reset policy remains a maintainer decision. Neither the token nor the file path is stored in workspace settings, recent history, or window session state. A built-in application relaunch removes the original token-file and remote-address options, remote project paths, and launch-only window flags, allowing normal session restoration. Remaining arguments are rebuilt from the desktop CLI’s declared options; unknown Chromium switches are not retained. Relaunches that rewrite these arguments bypass pending-update handlers that cannot honor the changed arguments. Restored authenticated windows require a new launch with the token file; unrelated windows restore according to the existing settings. Launches forwarded to an existing process are not added to its original command line. External launchers should always pass both options when restarting their environment.

The direct connection supplies the token through the existing remote authentication handshake. It is not embedded in the remote authority or workspace URI. Wrong-token rejection comes from the server's existing authentication mechanism. When the option is absent, connections that have no saved authentication requirement and resolver extensions retain their existing behavior.

## Tests

Token-file parsing, window credential bindings, restart arguments, and direct authority resolution are covered by the existing unit runners:

```sh
npm run test-node -- --run src/vs/platform/remote/test/node/remoteConnectionToken.test.ts --run src/vs/platform/remote/test/common/connectionToken.test.ts --run src/vs/platform/environment/test/node/argv.test.ts --run src/vs/server/test/node/serverConnectionToken.test.ts --run src/vs/workbench/services/extensions/test/common/directRemoteAuthority.test.ts
scripts/test.sh --run src/vs/platform/windows/test/electron-main/windowsStateHandler.test.ts
```

These helper tests do not exercise the complete desktop launch, IPC, window-reuse, or application-restart flow. Those flows still need manual integration validation.

On headless Linux, run the Electron tests under `xvfb-run -a`. If `ELECTRON_RUN_AS_NODE` is set in the shell, unset it for the test runner. Containers with limited shared memory may also need `--disable-dev-shm-usage`.
15 changes: 15 additions & 0 deletions src/vs/platform/remote/common/connectionToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

/** Whether a value is a non-empty token in the remote protocol's ASCII alphabet. */
export function isValidConnectionToken(value: unknown): value is string {
return typeof value === 'string' && value.length > 0 && !/[^0-9A-Za-z_-]/.test(value);
}

/** Parse a token file, allowing exactly one optional trailing LF or CRLF. */
export function parseConnectionTokenFile(contents: string): string | undefined {
const token = contents.replace(/\r?\n$/, '');
return isValidConnectionToken(token) ? token : undefined;
}
Loading