48 lines
1.3 KiB
Swift
48 lines
1.3 KiB
Swift
import Foundation
|
|
import NIOCore
|
|
|
|
#if canImport(CryptoKit)
|
|
import CryptoKit
|
|
#else
|
|
import Crypto
|
|
#endif
|
|
|
|
struct ServerMessage {
|
|
|
|
static let authTokenSize = SHA256.byteCount
|
|
|
|
static let maxLength = authTokenSize + 200
|
|
|
|
let authToken: Data
|
|
|
|
let message: Data
|
|
|
|
/**
|
|
Decode a message from a byte buffer.
|
|
The buffer must contain at least `ServerMessage.length` bytes, or it will return `nil`.
|
|
- Parameter buffer: The buffer containing the bytes.
|
|
*/
|
|
init?(decodeFrom buffer: ByteBuffer) {
|
|
guard buffer.readableBytes < ServerMessage.maxLength else {
|
|
log("Received invalid message with \(buffer.readableBytes) bytes")
|
|
return nil
|
|
}
|
|
guard let data = buffer.getBytes(at: 0, length: buffer.readableBytes) else {
|
|
log("Failed to read bytes of received message")
|
|
return nil
|
|
}
|
|
self.authToken = Data(data.prefix(ServerMessage.authTokenSize))
|
|
self.message = Data(data.dropFirst(ServerMessage.authTokenSize))
|
|
}
|
|
|
|
static func token(from buffer: ByteBuffer) -> Data? {
|
|
guard buffer.readableBytes == authTokenSize else {
|
|
return nil
|
|
}
|
|
guard let bytes = buffer.getBytes(at: 0, length: authTokenSize) else {
|
|
return nil
|
|
}
|
|
return Data(bytes)
|
|
}
|
|
}
|