Last active
December 19, 2024 02:22
-
-
Save clarkio/30328377b5f1e93ba6e227e78d5f87a2 to your computer and use it in GitHub Desktop.
Connecting to OBS Websocket Server with Authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const obsConfig = { | |
address: '127.0.0.1', | |
port: 4455, | |
password: 'your-password' | |
} | |
const socket = new WebSocket(`ws://${obsConfig.address}:${obsConfig.port}`); | |
const password = obsConfig.password; | |
socket.onopen = function(event) { | |
console.log('Connected to OBS WebSocket server'); | |
}; | |
socket.onclose = function(event) { | |
console.log('Disconnected from OBS WebSocket server'); | |
console.log('Reason:', event.reason); | |
console.log('Code:', event.code); | |
}; | |
socket.onerror = function(error) { | |
console.error('WebSocket error:', error); | |
}; | |
socket.onmessage = async function(event) { | |
console.log('Received message:', event.data); | |
const response = JSON.parse(event.data); | |
// If the authentication is required, send a response | |
if (response.d.authentication && response.op === 0) { | |
const salt = response.d.authentication.salt; | |
const challenge = response.d.authentication.challenge; | |
const secret = await sha256Hash(password + salt); | |
const authResponseHash = await sha256Hash(secret + challenge); | |
const payload = { | |
op: 1, | |
d: { | |
rpcVersion: 1, | |
authentication: authResponseHash, | |
} | |
} | |
socket.send(JSON.stringify(payload)); | |
} | |
}; | |
async function sha256Hash(inputText) { | |
const utf8 = new TextEncoder().encode(inputText); | |
const hashBuffer = await crypto.subtle.digest('SHA-256', utf8); | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
const base64Hash = btoa(String.fromCharCode(...hashArray)); | |
return base64Hash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment