Skip to content

Commit 9d84d92

Browse files
committed
Secure browser websocket connections with token authentication and origin validation
- verify if origin is a chrome extension - before launching browser, create ws-token file in `~user/.cwc` and copy it to extension's build directory `~user/.cwc/repository-[schema]/apps/browser/out`. Browser extension trying to connect, should read this file, attach value to url param 'token', and the `apps/editor/src/services/websocket-server-process.ts` should compare it with the `~user/.cwc/ws-token`
1 parent 8195795 commit 9d84d92

3 files changed

Lines changed: 80 additions & 3 deletions

File tree

‎apps/browser/src/background/websocket.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,17 @@ const ports_to_check = async (): Promise<number[]> => {
1010
return [DEFAULT_PORT, ...forwarded_ports]
1111
}
1212

13+
const get_ws_token = async (): Promise<string | null> => {
14+
try {
15+
const response = await fetch(chrome.runtime.getURL('ws-token'))
16+
if (!response.ok) return null
17+
const token = (await response.text()).trim()
18+
return token || null
19+
} catch {
20+
return null
21+
}
22+
}
23+
1324
const STALE_AFTER_MS = 20000
1425
const CONNECT_TIMEOUT_MS = 2000
1526
const RETRY_IDLE_MS = 5000
@@ -132,7 +143,16 @@ export const connect_websocket = async (port: number): Promise<void> => {
132143
}
133144

134145
try {
135-
const ws_url = `ws://localhost:${port}?client_type=${CLIENT_TYPE.BROWSER}`
146+
const token = await get_ws_token()
147+
if (is_busy(c)) return
148+
149+
const params = new URLSearchParams({
150+
client_type: CLIENT_TYPE.BROWSER
151+
})
152+
if (token) {
153+
params.set('token', token)
154+
}
155+
const ws_url = `ws://localhost:${port}?${params.toString()}`
136156

137157
const ws = new WebSocket(ws_url)
138158
c.ws = ws

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import * as crypto from 'crypto'
2+
import * as fs from 'fs'
23
import * as http from 'http'
4+
import * as os from 'os'
5+
import * as path from 'path'
36
import * as process from 'process'
47
const WebSocket = require('ws')
58
import { DEFAULT_PORT, CLIENT_TYPE } from '@shared/constants/websocket'
@@ -33,6 +36,19 @@ class WebSocketServer {
3336
const client_type = url.searchParams.get('client_type')
3437

3538
if (client_type === CLIENT_TYPE.BROWSER) {
39+
const origin = info.origin || info.req.headers.origin
40+
if (
41+
typeof origin !== 'string' ||
42+
!origin.startsWith('chrome-extension://')
43+
) {
44+
return cb(false, 403, 'Forbidden: Invalid origin')
45+
}
46+
47+
const token = url.searchParams.get('token')
48+
if (!this._verify_browser_token(token)) {
49+
return cb(false, 401, 'Unauthorized: Invalid token')
50+
}
51+
3652
if (
3753
this.browser_client &&
3854
this.browser_client.ws.readyState === WebSocket.OPEN
@@ -58,6 +74,22 @@ class WebSocketServer {
5874
console.log(`Starting WebSocket server process (PID: ${process.pid})`)
5975
}
6076

77+
private _verify_browser_token(token: string | null): boolean {
78+
if (!token) return false
79+
const token_path = path.join(os.homedir(), '.cwc', 'ws-token')
80+
try {
81+
if (!fs.existsSync(token_path)) return false
82+
const expected_token = fs.readFileSync(token_path, 'utf-8').trim()
83+
if (!expected_token) return false
84+
const token_buf = Buffer.from(token)
85+
const expected_buf = Buffer.from(expected_token)
86+
if (token_buf.length !== expected_buf.length) return false
87+
return crypto.timingSafeEqual(token_buf, expected_buf)
88+
} catch {
89+
return false
90+
}
91+
}
92+
6193
private _schedule_shutdown() {
6294
if (!this.shutdown_timer) {
6395
this.shutdown_timer = setTimeout(() => {

‎apps/editor/src/views/prompt/backend/message-handlers/handle-run-browser.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as vscode from 'vscode'
22
import * as path from 'path'
33
import * as os from 'os'
44
import * as fs from 'fs'
5+
import * as crypto from 'crypto'
56
import { spawn } from 'child_process'
67
import {
78
Browser,
@@ -17,7 +18,21 @@ const launch_browser = (params: {
1718
executable_path: string
1819
user_data_dir: string
1920
extension_path: string
21+
cwc_dir: string
2022
}) => {
23+
const token_path = path.join(params.cwc_dir, 'ws-token')
24+
let token = ''
25+
if (fs.existsSync(token_path)) {
26+
token = fs.readFileSync(token_path, 'utf-8').trim()
27+
}
28+
if (!token) {
29+
token = crypto.randomBytes(32).toString('hex')
30+
fs.writeFileSync(token_path, token, { mode: 0o600 })
31+
}
32+
if (fs.existsSync(params.extension_path)) {
33+
fs.copyFileSync(token_path, path.join(params.extension_path, 'ws-token'))
34+
}
35+
2136
const args = [
2237
`--user-data-dir=${params.user_data_dir}`,
2338
`--load-extension=${params.extension_path}`,
@@ -167,7 +182,12 @@ export const handle_run_browser = async (
167182
if (fs.existsSync(cached_path_file)) {
168183
const executable_path = fs.readFileSync(cached_path_file, 'utf-8').trim()
169184
if (fs.existsSync(executable_path)) {
170-
launch_browser({ executable_path, user_data_dir, extension_path })
185+
launch_browser({
186+
executable_path,
187+
user_data_dir,
188+
extension_path,
189+
cwc_dir
190+
})
171191
return
172192
}
173193
}
@@ -223,7 +243,12 @@ export const handle_run_browser = async (
223243
}
224244

225245
fs.writeFileSync(cached_path_file, executable_path)
226-
launch_browser({ executable_path, user_data_dir, extension_path })
246+
launch_browser({
247+
executable_path,
248+
user_data_dir,
249+
extension_path,
250+
cwc_dir
251+
})
227252
} catch (error: any) {
228253
if (error.message === 'Download cancelled') {
229254
return

0 commit comments

Comments
 (0)