Sesame-Server/Sources/App/API/ServerMessage.swift

48 lines
1.3 KiB
Swift
Raw Normal View History

2022-05-01 13:12:16 +02:00
import Foundation
import NIOCore
#if canImport(CryptoKit)
import CryptoKit
#else
import Crypto
#endif
struct ServerMessage {
static let authTokenSize = SHA256.byteCount
2023-08-09 16:26:07 +02:00
static let maxLength = authTokenSize + 200
2022-05-01 13:12:16 +02:00
let authToken: Data
2023-08-09 16:26:07 +02:00
let message: Data
2022-05-01 13:12:16 +02:00
/**
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) {
2023-08-09 16:26:07 +02:00
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")
2022-05-01 13:12:16 +02:00
return nil
}
self.authToken = Data(data.prefix(ServerMessage.authTokenSize))
2023-08-09 16:26:07 +02:00
self.message = Data(data.dropFirst(ServerMessage.authTokenSize))
2022-05-01 13:12:16 +02:00
}
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)
}
}