Skip to content

Commit 3ce7bec

Browse files
committed
Secure WebSocket server connections using a session token stored in a lockfile
- Update `websocket-manager.ts` and `websocket-server-process.ts` to implement a secure lockfile handshake where the server writes its PID and a randomly generated session token to a secure file in the extension's secure storage, and the editor reads this lockfile to verify the server's PID and authenticate the WebSocket connection using the token. ├── apps │ ├── browser │ │ ├── package.json │ │ └── src │ │ ├── background │ │ │ ├── message-handler.ts │ │ │ └── websocket.ts │ │ ├── content-scripts │ │ │ └── send-prompt-content-script │ │ │ └── utils │ │ │ └── add-apply-response-button.ts │ │ └── manifest.json │ ├── editor │ │ ├── package.json │ │ ├── src │ │ │ ├── commands │ │ │ │ └── apply-response-command │ │ │ │ ├── apply-response-command.ts │ │ │ │ └── response-processor │ │ │ │ ├── handlers │ │ │ │ │ ├── diff-handler.ts │ │ │ │ │ ├── fast-replace-handler.ts │ │ │ │ │ ├── patch-repair-handler.ts │ │ │ │ │ ├── restore-preview-handler.ts │ │ │ │ │ ├── search-replace-handler.ts │ │ │ │ │ └── truncated-handler.ts │ │ │ │ └── response-processor.ts │ │ │ ├── extension.ts │ │ │ └── services │ │ │ ├── websocket-manager.ts │ │ │ └── websocket-server-process.ts │ │ └── tsconfig.json │ └── web │ └── package.json ├── package.json └── packages ├── shared │ ├── package.json │ └── src │ ├── constants │ │ └── websocket.ts │ └── types │ └── websocket-message.ts └── ui └── package.json
1 parent 28d8fb9 commit 3ce7bec

2 files changed

Lines changed: 101 additions & 2 deletions

File tree

‎apps/editor/src/services/websocket-manager.ts‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as child_process from 'child_process'
2+
import * as fs from 'fs'
23
import * as http from 'http'
34
import * as net from 'net'
45
import * as path from 'path'
@@ -43,6 +44,13 @@ export class WebSocketManager {
4344
this._initialize_server()
4445
}
4546

47+
private get _lockfile_path(): string {
48+
return path.join(
49+
this.extension_context.globalStorageUri.fsPath,
50+
'websocket-lock.json'
51+
)
52+
}
53+
4654
private async _is_port_in_use(port: number): Promise<boolean> {
4755
return new Promise((resolve) => {
4856
const tester = net
@@ -79,13 +87,22 @@ export class WebSocketManager {
7987
)
8088

8189
try {
90+
const global_storage_path = this.extension_context.globalStorageUri.fsPath
91+
if (!fs.existsSync(global_storage_path)) {
92+
fs.mkdirSync(global_storage_path, { recursive: true })
93+
}
94+
8295
const spawned = child_process.spawn(
8396
process.execPath,
8497
[server_script_path],
8598
{
8699
detached: true,
87100
stdio: 'ignore',
88-
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
101+
env: {
102+
...process.env,
103+
ELECTRON_RUN_AS_NODE: '1',
104+
CWC_WEBSOCKET_LOCKFILE: this._lockfile_path
105+
}
89106
}
90107
)
91108

@@ -166,9 +183,51 @@ export class WebSocketManager {
166183
this._schedule_reconnect()
167184
return
168185
}
186+
} else {
187+
try {
188+
await this._wait_for_server_ready(5, 500)
189+
} catch (error) {
190+
Logger.error({
191+
function_name: '_connect_as_client',
192+
message:
193+
'Existing WebSocket server is not responding to health check',
194+
data: error
195+
})
196+
}
169197
}
170198

171-
const ws_url = `ws://localhost:${this.port}?client_type=${this.client_type}`
199+
let token = ''
200+
try {
201+
if (fs.existsSync(this._lockfile_path)) {
202+
const lock_data = JSON.parse(
203+
fs.readFileSync(this._lockfile_path, 'utf8')
204+
)
205+
try {
206+
process.kill(lock_data.pid, 0)
207+
token = lock_data.token
208+
} catch (e: any) {
209+
if (e.code === 'ESRCH') {
210+
Logger.warn({
211+
function_name: '_connect_as_client',
212+
message: `Process ${lock_data.pid} is not running.`
213+
})
214+
} else {
215+
token = lock_data.token
216+
}
217+
}
218+
}
219+
} catch (e) {
220+
Logger.error({
221+
function_name: '_connect_as_client',
222+
message: 'Failed to read lockfile',
223+
data: e
224+
})
225+
}
226+
227+
let ws_url = `ws://localhost:${this.port}?client_type=${this.client_type}`
228+
if (token) {
229+
ws_url += `&token=${token}`
230+
}
172231
this.client = new WebSocket.WebSocket(ws_url)
173232

174233
this.client.on('open', () => {

‎apps/editor/src/services/websocket-server-process.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as crypto from 'crypto'
2+
import * as fs from 'fs'
23
import * as http from 'http'
34
import * as process from 'process'
45
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -28,8 +29,27 @@ class WebSocketServer {
2829
private connections: Set<WebSocket> = new Set()
2930
private server: http.Server
3031
private wss: any
32+
private lockfile_path: string | null = null
33+
private session_token: string | null = null
3134

3235
constructor() {
36+
this.lockfile_path = process.env.CWC_WEBSOCKET_LOCKFILE || null
37+
if (this.lockfile_path) {
38+
this.session_token = crypto.randomBytes(32).toString('hex')
39+
try {
40+
fs.writeFileSync(
41+
this.lockfile_path,
42+
JSON.stringify({
43+
pid: process.pid,
44+
token: this.session_token
45+
}),
46+
{ mode: 0o600 }
47+
)
48+
} catch (e) {
49+
console.error('Failed to write lockfile', e)
50+
}
51+
}
52+
3353
this.server = this._create_http_server()
3454
this.wss = new WebSocket.Server({
3555
server: this.server,
@@ -99,6 +119,14 @@ class WebSocketServer {
99119

100120
const is_browser_client = client_type == CLIENT_TYPE.BROWSER
101121

122+
if (!is_browser_client && this.session_token) {
123+
const token = url.searchParams.get('token')
124+
if (token !== this.session_token) {
125+
ws.close(1008, 'Invalid session token')
126+
return
127+
}
128+
}
129+
102130
if (is_browser_client) {
103131
this._handle_browser_connection(ws, url)
104132
} else {
@@ -316,6 +344,18 @@ class WebSocketServer {
316344
})
317345
this.wss.close()
318346
this.server.close(() => {
347+
if (this.lockfile_path) {
348+
try {
349+
if (fs.existsSync(this.lockfile_path)) {
350+
const data = JSON.parse(fs.readFileSync(this.lockfile_path, 'utf8'))
351+
if (data.pid === process.pid) {
352+
fs.unlinkSync(this.lockfile_path)
353+
}
354+
}
355+
} catch (e) {
356+
console.error('Failed to cleanup lockfile', e)
357+
}
358+
}
319359
process.exit(0)
320360
})
321361
}

0 commit comments

Comments
 (0)