Something went wrong. Try again.
The WebSocket Protocol (RFC 6455) for Zig: framing, a client, and a server handshake on zig-http
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The parts of the opening handshake that both ends share.//!//! Separate from `handshake.zig` for one reason: that file is the server's//! half and is written against zig-http, and a client has no business//! depending on an HTTP server library to compute a digest. Everything here//! is the RFC's own constants and the one function that turns a key into the//! answer to it.
const std = @import("std");
/// §4.2.2 step 5.4's "globally unique identifier", which exists so that a/// server cannot be tricked into producing a valid `Sec-WebSocket-Accept` for/// a key it was given by something that is not a WebSocket client.pub const guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/// The only version of this protocol. §4.4 leaves room for others and none/// was ever defined.pub const version = "13";
/// The `Upgrade` token, and the value RFC 8441 §5 requires in `:protocol`.pub const protocol_name = "websocket";
/// How long `acceptToken` writes: base64 of a 20-octet SHA-1 digest.pub const accept_token_len = 28;
/// §4.2.2: base64(SHA1(key ++ guid)).////// The digest proves nothing about anybody's identity and is not meant to --/// it proves that whatever answered had read the request and knew the rule,/// which is enough to stop a server that merely echoes headers from being/// mistaken for a WebSocket endpoint, and a client that checks it from being/// talked into framing messages at one.pub fn acceptToken(key: []const u8, out: *[accept_token_len]u8) []const u8 { var sha1: std.crypto.hash.Sha1 = .init(.{}); sha1.update(key); sha1.update(guid); var digest: [std.crypto.hash.Sha1.digest_length]u8 = undefined; sha1.final(&digest); return std.base64.standard.Encoder.encode(out, &digest);}
test "RFC 6455 1.3: the example key and its answer" { var out: [accept_token_len]u8 = undefined; try std.testing.expectEqualStrings( "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", acceptToken("dGhlIHNhbXBsZSBub25jZQ==", &out), );}