SPB Git

Repository Public

WebhookSignature.swift 3.0 KB 49 lines swift

1import CryptoKit2import Foundation34/// Verification of `SPMail-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw body)>` (docs/API.md §11.4).5public enum SPMailWebhook {6    /// True when the signature matches the RAW request body and its timestamp is within `tolerance` seconds of `now`.7    /// - Parameter payload: the body exactly as received — never a re-serialised JSON.8    public static func verify(payload: Data, header: String?, secret: String, tolerance: TimeInterval = 300, now: Date = Date()) -> Bool {9        check(payload: payload, header: header, secret: secret, tolerance: tolerance, now: now) == nil10    }1112    /// Verifies the signature, then decodes the event envelope. Throws `SPMailError.invalidSignature` otherwise.13    public static func constructEvent(payload: Data, header: String?, secret: String, tolerance: TimeInterval = 300, now: Date = Date()) throws -> WebhookEvent {14        if let reason = check(payload: payload, header: header, secret: secret, tolerance: tolerance, now: now) {15            throw SPMailError.invalidSignature(reason)16        }17        do { return try JSONDecoder().decode(WebhookEvent.self, from: payload) } catch { throw SPMailError.invalidSignature("payload is not a valid event") }18    }1920    /// Builds a valid header value (for tests of your own receiver).21    public static func sign(payload: Data, secret: String, timestamp: Date = Date()) -> String {22        let t = String(Int(timestamp.timeIntervalSince1970))23        return "t=\(t),v1=\(hex(mac(payload: payload, timestamp: t, secret: secret)))"24    }2526    private static func mac(payload: Data, timestamp: String, secret: String) -> [UInt8] {27        var h = HMAC<SHA256>(key: SymmetricKey(data: Data(secret.utf8)))28        h.update(data: Data("\(timestamp).".utf8))29        h.update(data: payload)30        return Array(h.finalize())31    }32    private static func hex(_ bytes: [UInt8]) -> String { bytes.map { String(format: "%02x", $0) }.joined() }3334    private static func check(payload: Data, header: String?, secret: String, tolerance: TimeInterval, now: Date) -> String? {35        guard let header, let m = header.wholeMatch(of: /t=(\d{1,12}),v1=([0-9a-f]{64})/) else { return "missing or malformed SPMail-Signature header" }36        guard !secret.isEmpty else { return "no webhook secret given" }37        guard let t = TimeInterval(m.1), abs(now.timeIntervalSince1970 - t) <= tolerance else { return "timestamp outside the tolerance window" }38        var given: [UInt8] = []39        var rest = Substring(m.2)40        while !rest.isEmpty { given.append(UInt8(rest.prefix(2), radix: 16)!); rest = rest.dropFirst(2) }41        let expected = mac(payload: payload, timestamp: String(m.1), secret: secret)42        // Constant-time comparison.43        guard given.count == expected.count else { return "signature mismatch" }44        var diff: UInt8 = 045        for i in 0..<expected.count { diff |= expected[i] ^ given[i] }46        return diff == 0 ? nil : "signature mismatch"47    }48}49
Files main
Menu

Theme