Skip to content

Commit d840974

Browse files
committed
Implement shared token authentication for WebSocket connections
- [Pasted text] - we run browser extension also in 'unpacked' variant, locally for development purposes and it should be allowed to connect to. use .env variables - use dotenv package instead of extracting manually - .env is not being read properly by `apps/editor/src/services/websocket-server-process.ts` ├── apps │ └── editor │ ├── .env-sample │ ├── .gitignore │ ├── package.json │ ├── src │ │ ├── services │ │ │ ├── websocket-manager.ts │ │ │ └── websocket-server-process.ts │ │ └── utils │ │ └── shared-token.ts │ └── webpack.config.ts └── packages └── shared └── src └── constants └── websocket.ts
1 parent e9abd01 commit d840974

7 files changed

Lines changed: 78 additions & 11 deletions

File tree

‎apps/editor/.env-sample‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DEV_CHROME_EXTENSION_ID=gllgiagogfbdinjgfibkndhdpgpdjjpf

‎apps/editor/.gitignore‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/out
22
/node_modules
33
/*.vsix
4-
/README.md
4+
/README.md
5+
/.env

‎apps/editor/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1318,6 +1318,7 @@
13181318
"dayjs": "^1.11.10",
13191319
"diff": "^8.0.4",
13201320
"dompurify": "^3.4.14",
1321+
"dotenv": "^16.4.5",
13211322
"glob": "^11.1.0",
13221323
"he": "^1.2.0",
13231324
"ignore": "^6.0.2",

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { ConfigWebConfigurationFormat } from '@/utils/web-configuration-format-c
1818
import { LAST_SELECTED_BROWSER_ID_STATE_KEY } from '@/constants/state-keys'
1919
import { ApplyResponseCommandArgs } from '@/commands/apply-response-command/response-processor'
2020
import { t } from '@/i18n'
21+
import { get_or_create_shared_token } from '../utils/shared-token'
2122

2223
/**
2324
* Bridges the current workspace window and a WebSockets server
@@ -26,7 +27,6 @@ import { t } from '@/i18n'
2627
export class WebSocketManager {
2728
private extension_context: vscode.ExtensionContext
2829
private port: number = DEFAULT_PORT
29-
private client_type: string = CLIENT_TYPE.EDITOR
3030
private client: WebSocket.WebSocket | null = null
3131
private _on_connection_status_change: vscode.EventEmitter<boolean> =
3232
new vscode.EventEmitter<boolean>()
@@ -168,7 +168,8 @@ export class WebSocketManager {
168168
}
169169
}
170170

171-
const ws_url = `ws://localhost:${this.port}?client_type=${this.client_type}`
171+
const token = get_or_create_shared_token()
172+
const ws_url = `ws://localhost:${this.port}?client_type=${CLIENT_TYPE.EDITOR}&token=${token}`
172173
this.client = new WebSocket.WebSocket(ws_url)
173174

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

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

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import * as crypto from 'crypto'
22
import * as http from 'http'
3+
import * as path from 'path'
34
import * as process from 'process'
5+
import * as dotenv from 'dotenv'
46
// eslint-disable-next-line @typescript-eslint/no-var-requires
57
const WebSocket = require('ws')
6-
78
import { DEFAULT_PORT, CLIENT_TYPE } from '@shared/constants/websocket'
89

10+
dotenv.config({ path: path.join(__dirname, '..', '.env') })
11+
912
interface BrowserClient {
1013
ws: WebSocket
1114
version: string
@@ -36,15 +39,50 @@ class WebSocketServer {
3639
server: this.server,
3740
maxPayload: 10 * 1024 * 1024,
3841
verifyClient: (info: any, cb: any) => {
39-
const origin = info.req.headers.origin
40-
if (origin) {
41-
const allowed_prefixes = ['chrome-extension://', 'moz-extension://']
42-
if (!allowed_prefixes.some((prefix) => origin.startsWith(prefix))) {
43-
cb(false, 403, 'Forbidden')
44-
return
42+
const url = new URL(info.req.url, `http://localhost:${DEFAULT_PORT}`)
43+
const client_type = url.searchParams.get('client_type')
44+
45+
if (client_type == CLIENT_TYPE.BROWSER) {
46+
const origin = info.req.headers.origin
47+
48+
// 1. Chrome / Edge / Chromium: Strict Exact Match
49+
if (origin == 'chrome-extension://ljookipcanaglfaocjbgdicfbdhhjffp') {
50+
return cb(true)
4551
}
52+
53+
if (
54+
process.env.DEV_CHROME_EXTENSION_ID &&
55+
origin ==
56+
`chrome-extension://${process.env.DEV_CHROME_EXTENSION_ID}`
57+
) {
58+
return cb(true)
59+
}
60+
61+
// 2. Firefox: Wildcard fallback
62+
// (Firefox extensions get random origins, making exact matches impossible)
63+
if (origin && origin.startsWith('moz-extension://')) {
64+
return cb(true)
65+
}
66+
67+
return cb(false, 403, 'Forbidden: Invalid Origin')
68+
}
69+
70+
if (client_type == CLIENT_TYPE.EDITOR) {
71+
// 3. Editors: Enforce the shared file token
72+
const provided_token = url.searchParams.get('token')
73+
const {
74+
get_or_create_shared_token
75+
// eslint-disable-next-line @typescript-eslint/no-var-requires
76+
} = require('../utils/shared-token')
77+
const expected_token = get_or_create_shared_token()
78+
79+
if (provided_token && provided_token == expected_token) {
80+
return cb(true)
81+
}
82+
return cb(false, 401, 'Unauthorized: Invalid token')
4683
}
47-
cb(true)
84+
85+
cb(false, 400, 'Bad Request')
4886
}
4987
})
5088
this._setup_websocket_server()
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import * as os from 'os'
2+
import * as path from 'path'
3+
import * as fs from 'fs'
4+
import * as crypto from 'crypto'
5+
6+
export const get_or_create_shared_token = (): string => {
7+
const token_dir = path.join(os.homedir(), '.cwc')
8+
const token_path = path.join(token_dir, '.websocket-token')
9+
10+
if (fs.existsSync(token_path)) {
11+
return fs.readFileSync(token_path, 'utf8').trim()
12+
}
13+
14+
const token = crypto.randomBytes(32).toString('hex')
15+
if (!fs.existsSync(token_dir)) {
16+
fs.mkdirSync(token_dir, { recursive: true, mode: 0o700 })
17+
}
18+
19+
// 0o600 restricts access exclusively to the current user
20+
fs.writeFileSync(token_path, token, { mode: 0o600 })
21+
return token
22+
}

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)