src/vs/platform/agentHost/node/localAgentHostMetadata.ts

199 LOC · 148 covered · 51 uncovered · 24 ranges · 4 concepts · 3 introducers · 5 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the filesrc/vs/base/common/validation.ts · 396 LOCcommon/validation.tslocalAgentHostMetadata.ts ×4 · 19 introduced LOClocalAgentHostMetadata.t…localAgentHostMetadata.ts ×6 · 34 introduced LOClocalAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata writes owner-only socket directory permissions|occurrence=1, localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata uses a bounded path under the system temporary directory|occurrence=1 · 0 introduced LOClocalAgentHostMetadata.t…localAgentHostMetadata.ts ×14 · 103 introduced LOClocalAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata atomically replaces and owner-checks metadata|occurrence=1 · introduced test · mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata atomically replaces and owner-checks metadata|occurrence=1localAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata creates scoped endpoint metadata|occurrence=1 · introduced test · mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata creates scoped endpoint metadata|occurrence=1localAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata uses a bounded path under the system temporary directory|occurrence=1 · introduced test · mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata uses a bounded path under the system temporary directory|occurrence=1localAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata writes owner-only metadata permissions|occurrence=1 · introduced test · mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata writes owner-only metadata permissions|occurrence=1localAgentHostMetadata.t…localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata writes owner-only socket directory permissions|occurrence=1 · introduced test · mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/localAgentHostMetadata.test|title=Local Agent Host Endpoint Metadata writes owner-only socket directory permissions|occurrence=1localAgentHostMetadata.t…Focused file · src/vs/platform/agentHost/node/localAgentHostMetadata.ts · 199 LOCnode/localAgentHostMetad…

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- localAgentHostMetadata.ts ×14
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { execFile } from 'child_process';
7 > import { createHash, randomBytes } from 'crypto';
8 > import * as fs from 'fs';
9 > import * as os from 'os';
10 > import { join } from '../../../base/common/path.js';
11 > import { vArray, vLiteral, vNumber, vObj, vString } from '../../../base/common/validation.js';
12 > import { PROTOCOL_VERSION } from '../common/state/protocol/version/registry.js';
13 >
14 > const metadataSchemaVersion = 1;
15 > const metadataDirectoryName = 'agent-host';
16 > const endpointDirectoryName = 'local-endpoint';
17 > const metadataFileName = 'metadata.json';
18 >
19 > export interface ILocalAgentHostEndpointMetadata {
20 > readonly type: 'editor';
21 > readonly schemaVersion: typeof metadataSchemaVersion;
22 > readonly pid: number;
23 > readonly instanceId: string;
24 > readonly endpointPath: string;
25 > readonly connectionToken: string;
26 > readonly protocolVersion: string;
27 > }
28 >
29 > const metadataValidator = vArray(vObj({
30 > type: vLiteral('editor'),
31 > schemaVersion: vNumber(),
32 > pid: vNumber(),
33 > instanceId: vString(),
34 > endpointPath: vString(),
35 > connectionToken: vString(),
36 > protocolVersion: vString(),
37 > }));
38 >
39 > export function createLocalAgentHostEndpointMetadata(userDataPath: string): ILocalAgentHostEndpointMetadata {
40 > const instanceId = randomBytes(16).toString('base64url');
41 > return {
42 > type: 'editor',
43 > schemaVersion: metadataSchemaVersion,
44 > pid: process.pid,
45 > instanceId,
46 > endpointPath: getEndpointPath(userDataPath, instanceId),
47 > connectionToken: randomBytes(32).toString('base64url'),
48 > protocolVersion: PROTOCOL_VERSION,
49 > };
50 > }
51 >
52 > export async function prepareLocalAgentHostEndpointMetadataDirectory(userDataPath: string): Promise<void> {
53 > const directory = getMetadataDirectory(userDataPath);
54 > await fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
55 > const stat = await fs.promises.lstat(directory);
56 > if (!stat.isDirectory() || stat.isSymbolicLink()) {
57 throw new Error(`Local agent host endpoint metadata directory is not a directory: ${directory}`);
58 }
60 > if (process.platform === 'win32') {
61 await applyWindowsOwnerOnlyAcl(directory);
63 > if (process.getuid && stat.uid !== process.getuid()) {
64 throw new Error(`Local agent host endpoint metadata directory is not owned by the current user: ${directory}`);
65 }
66 > await fs.promises.chmod(directory, 0o700); localAgentHostMetadata.ts ×14
67 > }
68 > }
69 >
70 > export async function prepareLocalAgentHostEndpointSocketDirectory(userDataPath: string): Promise<void> {
71 > if (process.platform !== 'win32') {
72 > const directory = getSocketDirectory(userDataPath);
73 > await fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
74 > const stat = await fs.promises.lstat(directory);
75 > if (!stat.isDirectory() || stat.isSymbolicLink()) {
76 throw new Error(`Local agent host endpoint socket directory is not a directory: ${directory}`);
77 }
78 > if (process.getuid && stat.uid !== process.getuid()) { localAgentHostMetadata.ts ×14
79 throw new Error(`Local agent host endpoint socket directory is not owned by the current user: ${directory}`);
80 }
81 > await fs.promises.chmod(directory, 0o700); localAgentHostMetadata.ts ×14
82 > }
83 > }
84 >
85 > export async function publishLocalAgentHostEndpointMetadata(userDataPath: string, metadata: ILocalAgentHostEndpointMetadata): Promise<void> { localAgentHostMetadata.ts ×6
86 > const metadataPath = getMetadataPath(userDataPath);
87 > const temporaryPath = `${metadataPath}.${metadata.instanceId}.tmp`;
88 > const entries = readMetadata(metadataPath).filter(entry => entry.pid !== metadata.pid || entry.type !== metadata.type);
89 > entries.push(metadata);
90 > const handle = await fs.promises.open(temporaryPath, 'wx', 0o600);
91 > try {
92 > await handle.writeFile(JSON.stringify(entries), 'utf8');
93 > await handle.sync();
94 > } finally {
95 > await handle.close();
96 > }
97 >
98 > try {
99 > await fs.promises.rename(temporaryPath, metadataPath);
100 > } finally {
101 > await fs.promises.rm(temporaryPath, { force: true });
102 > }
103 > }
105 > export function cleanupLocalAgentHostEndpointMetadataSync(userDataPath: string, owner: ILocalAgentHostEndpointMetadata): void {
106 > const metadataPath = getMetadataPath(userDataPath); localAgentHostMetadata.ts ×4
107 > const entries = readMetadata(metadataPath);
108 > const remaining = entries.filter(entry => entry.pid !== owner.pid || entry.instanceId !== owner.instanceId || entry.type !== owner.type);
109 > if (remaining.length === entries.length) {
110 > return;
111 > }
112 > if (remaining.length === 0) {
113 > fs.rmSync(metadataPath, { force: true });
114 > } else {
115 fs.writeFileSync(metadataPath, JSON.stringify(remaining), { encoding: 'utf8', mode: 0o600 });
116 }
119 > export function cleanupLocalAgentHostEndpointSocketSync(endpointPath: string): void {
120 if (process.platform !== 'win32') {
121 fs.rmSync(endpointPath, { force: true });
122 }
123 }
125 > function getMetadataDirectory(userDataPath: string): string {
126 > return join(userDataPath, metadataDirectoryName, endpointDirectoryName);
127 > }
128 >
129 > function getMetadataPath(userDataPath: string): string { localAgentHostMetadata.ts ×6
130 > return join(getMetadataDirectory(userDataPath), metadataFileName);
131 > }
133 > function getSocketDirectory(userDataPath: string): string {
134 > const owner = process.getuid?.().toString() ?? '';
135 > const hash = createHash('sha256').update(`${owner}:${userDataPath}`).digest('hex').slice(0, 12);
136 > return join(os.tmpdir(), `vscode-ah-${hash}`);
137 > }
138 >
139 > function getEndpointPath(userDataPath: string, instanceId: string): string {
140 > if (process.platform === 'win32') {
141 const userDataHash = createHash('sha256').update(userDataPath).digest('hex');
142 return `\\\\.\\pipe\\vscode-agent-host-${userDataHash}-${instanceId}`;
143 }
144 > return join(getSocketDirectory(userDataPath), `${instanceId}.sock`); localAgentHostMetadata.ts ×14
145 > }
146 >
147 > function readMetadata(path: string): ILocalAgentHostEndpointMetadata[] { localAgentHostMetadata.ts ×6
148 > try {
149 > const stat = fs.lstatSync(path);
150 > if (!stat.isFile() || stat.isSymbolicLink()) {
151 return [];
152 }
153 > const result = metadataValidator.validate(JSON.parse(fs.readFileSync(path, 'utf8'))); localAgentHostMetadata.ts ×4
154 > if (result.error) {
155 return [];
156 }
157 > return result.content localAgentHostMetadata.ts ×4
158 > .filter(entry => entry.schemaVersion === metadataSchemaVersion)
159 > .map(entry => ({ ...entry, schemaVersion: metadataSchemaVersion }));
160 > } catch (error) { localAgentHostMetadata.ts ×6
161 > if (isNotFound(error) || error instanceof SyntaxError) {
162 > return [];
163 > }
164 throw error;
165 }
168 async function applyWindowsOwnerOnlyAcl(path: string): Promise<void> {
169 const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;
170 if (!systemRoot) {
171 throw new Error('Unable to resolve the Windows system directory for local agent host metadata.');
172 }
173 const systemDirectory = join(systemRoot, 'System32');
174 const whoAmI = await runWindowsCommand(join(systemDirectory, 'whoami.exe'), ['/user', '/fo', 'csv', '/nh']);
175 const sid = whoAmI.match(/S-\d+(?:-\d+)+/)?.[0];
176 if (!sid) {
177 throw new Error('Unable to determine the current Windows user SID for local agent host metadata.');
178 }
179 const icacls = join(systemDirectory, 'icacls.exe');
180 await runWindowsCommand(icacls, [path, '/reset']);
181 await runWindowsCommand(icacls, [
182 path,
183 '/inheritance:r',
184 '/grant:r',
185 `*${sid}:(OI)(CI)F`,
186 '*S-1-5-18:(OI)(CI)F',
187 '*S-1-5-32-544:(OI)(CI)F',
188 ]);
189 }
191 function runWindowsCommand(command: string, args: readonly string[]): Promise<string> {
192 return new Promise((resolve, reject) => {
193 execFile(command, [...args], { encoding: 'utf8', windowsHide: true }, (error, stdout) => error ? reject(error) : resolve(String(stdout)));
194 });
195 }
197 > function isNotFound(error: unknown): boolean { localAgentHostMetadata.ts ×6
198 > return (error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT';
199 > }