Merge pull request 'security(transport): subprotocol + Authorization header for webchat auth' (#2) from feat/webchat-auth-hardening into main

This commit is contained in:
serge 2026-04-27 16:36:15 +03:00
commit c5d1880589

View File

@ -52,13 +52,19 @@ export function createTransport(opts: TransportOpts): Transport {
function connectWs() {
if (closed) return;
const wsUrl =
opts.serverUrl.replace(/^http/, 'ws') +
`/webchat/ws?botId=${encodeURIComponent(opts.botId)}` +
`&apiKey=${encodeURIComponent(opts.apiKey)}` +
`&visitorId=${encodeURIComponent(opts.visitorId)}`;
// The browser WebSocket constructor does NOT accept custom headers, so
// we encode credentials into the Sec-WebSocket-Protocol list (the
// standard workaround). The bot reads `req.headers['sec-websocket-
// protocol']` and parses these tokens. See bot's `webchat/subprotocol.ts`.
const wsUrl = opts.serverUrl.replace(/^http/, 'ws') + '/webchat/ws';
const subprotocols = [
'messenzy.v1',
`messenzy-bot.${opts.botId}`,
`messenzy-visitor.${opts.visitorId}`,
`messenzy-key.${opts.apiKey}`,
];
try {
ws = new WebSocket(wsUrl);
ws = new WebSocket(wsUrl, subprotocols);
} catch {
onWsClose();
return;
@ -118,14 +124,19 @@ export function createTransport(opts: TransportOpts): Transport {
async function startPolling() {
pollTimer = setInterval(async () => {
if (closed) return;
// HTTP fallback uses Authorization: Bearer (browser fetch DOES allow
// custom headers, unlike the WebSocket constructor). botId/visitorId
// are public identifiers and stay in the query string.
const url =
`${opts.serverUrl}/webchat/history?` +
`botId=${encodeURIComponent(opts.botId)}` +
`&apiKey=${encodeURIComponent(opts.apiKey)}` +
`&visitorId=${encodeURIComponent(opts.visitorId)}` +
(lastSeenAt ? `&since=${encodeURIComponent(lastSeenAt)}` : '');
try {
const res = await fetch(url, { credentials: 'omit' });
const res = await fetch(url, {
credentials: 'omit',
headers: { authorization: `Bearer ${opts.apiKey}` },
});
if (!res.ok) return;
const data = (await res.json()) as {
messages?: Array<{ id: string; text: string; at: string }>;
@ -153,10 +164,12 @@ export function createTransport(opts: TransportOpts): Transport {
try {
await fetch(`${opts.serverUrl}/webchat/msg`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
headers: {
'content-type': 'application/json',
authorization: `Bearer ${opts.apiKey}`,
},
body: JSON.stringify({
botId: opts.botId,
apiKey: opts.apiKey,
visitorId: opts.visitorId,
text: msg.text,
idempotency_key: msg.id,