|
1 | 1 | import * as crypto from 'crypto' |
2 | 2 | import * as http from 'http' |
| 3 | +import * as path from 'path' |
3 | 4 | import * as process from 'process' |
| 5 | +import * as dotenv from 'dotenv' |
4 | 6 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
5 | 7 | const WebSocket = require('ws') |
6 | | - |
7 | 8 | import { DEFAULT_PORT, CLIENT_TYPE } from '@shared/constants/websocket' |
8 | 9 |
|
| 10 | +dotenv.config({ path: path.join(__dirname, '..', '.env') }) |
| 11 | + |
9 | 12 | interface BrowserClient { |
10 | 13 | ws: WebSocket |
11 | 14 | version: string |
@@ -36,15 +39,50 @@ class WebSocketServer { |
36 | 39 | server: this.server, |
37 | 40 | maxPayload: 10 * 1024 * 1024, |
38 | 41 | 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) |
45 | 51 | } |
| 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') |
46 | 83 | } |
47 | | - cb(true) |
| 84 | + |
| 85 | + cb(false, 400, 'Bad Request') |
48 | 86 | } |
49 | 87 | }) |
50 | 88 | this._setup_websocket_server() |
|
0 commit comments