vlcn-io / js

Components to build apps in JavaScript atop cr-sqlite
MIT License
54 stars 6 forks source link

Sec Header Decoding #34

Closed thomaswright closed 11 months ago

thomaswright commented 11 months ago

Hi, I'm testing out the vite starter example https://github.com/vlcn-io/vite-starter and have encountered an issue with the ws request header decoding:

function pullSecHeaders(request) {
  const proto = request.headers["sec-websocket-protocol"];
  if (proto == null) {
    throw new Error("Expected sec-websocket-protocol header");
  }
  const entries = proto?.split(",");
  const options = {};
  for (const entry of entries) {
    const [key, value] = atob(entry).split("=");
    options[key] = value;
  }
  return options;
}

The options output for a multi key object like "auth=myAuthToken,room=myRoomId" will be { auth: 'myAuthToken,room' }.

If we move the decode prior to the comma split this fixes the issue.

function pullSecHeaders(request) {
  const proto = request.headers["sec-websocket-protocol"];
  if (proto == null) {
    throw new Error("Expected sec-websocket-protocol header");
  }
  const entries = atob(proto).split(",");
  const options = {};
  for (const entry of entries) {
    const [key, value] = entry.split("=");
    options[key] = value;
  }
  return options;
}

Now the output is as expected: { auth: 'myAuthToken', room: 'myRoomId' }

thomaswright commented 11 months ago

https://github.com/vlcn-io/js/blob/705f6d2409d84c58c7953276e6b9102c2c08501b/packages/ws-server/src/index.ts#L104

tantaman commented 11 months ago

oops, you're right. The entire string is base64 encoded -- https://github.com/vlcn-io/js/blob/705f6d2409d84c58c7953276e6b9102c2c08501b/packages/ws-client/src/transport/WebSocketTransport.ts#L43

rather than individual parts.

thanks for catching this.

tantaman commented 11 months ago

fixes is checked in. Will have to roll a new release at some point.

thomaswright commented 11 months ago

Great! I'll check it out. Thanks for making this project - it looks really interesting.