File size: 6,993 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import CryptoKit
import Foundation

private struct DirectGatewayPushRegistrationPayload: Encodable {
    var transport: String = PushTransportMode.direct.rawValue
    var token: String
    var topic: String
    var environment: String
}

private struct RelayGatewayPushRegistrationPayload: Encodable {
    var transport: String = PushTransportMode.relay.rawValue
    var relayHandle: String
    var sendGrant: String
    var gatewayDeviceId: String
    var installationId: String
    var topic: String
    var environment: String
    var distribution: String
    var tokenDebugSuffix: String?
}

struct PushRelayGatewayIdentity: Codable {
    var deviceId: String
    var publicKey: String
}

actor PushRegistrationManager {
    private let buildConfig: PushBuildConfig
    private let relayClient: PushRelayClient?

    var usesRelayTransport: Bool {
        self.buildConfig.transport == .relay
    }

    init(buildConfig: PushBuildConfig = .current) {
        self.buildConfig = buildConfig
        self.relayClient = buildConfig.relayBaseURL.map { PushRelayClient(baseURL: $0) }
    }

    func makeGatewayRegistrationPayload(
        apnsTokenHex: String,
        topic: String,
        gatewayIdentity: PushRelayGatewayIdentity?)
    async throws -> String {
        switch self.buildConfig.transport {
        case .direct:
            return try Self.encodePayload(
                DirectGatewayPushRegistrationPayload(
                    token: apnsTokenHex,
                    topic: topic,
                    environment: self.buildConfig.apnsEnvironment.rawValue))
        case .relay:
            guard let gatewayIdentity else {
                throw PushRelayError.relayMisconfigured("Missing gateway identity for relay registration")
            }
            return try await self.makeRelayPayload(
                apnsTokenHex: apnsTokenHex,
                topic: topic,
                gatewayIdentity: gatewayIdentity)
        }
    }

    private func makeRelayPayload(
        apnsTokenHex: String,
        topic: String,
        gatewayIdentity: PushRelayGatewayIdentity)
    async throws -> String {
        guard self.buildConfig.distribution == .official else {
            throw PushRelayError.relayMisconfigured(
                "Relay transport requires OpenClawPushDistribution=official")
        }
        guard self.buildConfig.apnsEnvironment == .production else {
            throw PushRelayError.relayMisconfigured(
                "Relay transport requires OpenClawPushAPNsEnvironment=production")
        }
        guard let relayClient = self.relayClient else {
            throw PushRelayError.relayBaseURLMissing
        }
        guard let bundleId = Bundle.main.bundleIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines),
              !bundleId.isEmpty
        else {
            throw PushRelayError.relayMisconfigured("Missing bundle identifier for relay registration")
        }
        guard let installationId = GatewaySettingsStore.loadStableInstanceID()?
            .trimmingCharacters(in: .whitespacesAndNewlines),
              !installationId.isEmpty
        else {
            throw PushRelayError.relayMisconfigured("Missing stable installation ID for relay registration")
        }

        let tokenHashHex = Self.sha256Hex(apnsTokenHex)
        let relayOrigin = relayClient.normalizedBaseURLString
        if let stored = PushRelayRegistrationStore.loadRegistrationState(),
           stored.installationId == installationId,
           stored.gatewayDeviceId == gatewayIdentity.deviceId,
           stored.relayOrigin == relayOrigin,
           stored.lastAPNsTokenHashHex == tokenHashHex,
           !Self.isExpired(stored.relayHandleExpiresAtMs)
        {
            return try Self.encodePayload(
                RelayGatewayPushRegistrationPayload(
                    relayHandle: stored.relayHandle,
                    sendGrant: stored.sendGrant,
                    gatewayDeviceId: gatewayIdentity.deviceId,
                    installationId: installationId,
                    topic: topic,
                    environment: self.buildConfig.apnsEnvironment.rawValue,
                    distribution: self.buildConfig.distribution.rawValue,
                    tokenDebugSuffix: stored.tokenDebugSuffix))
        }

        let response = try await relayClient.register(
            installationId: installationId,
            bundleId: bundleId,
            appVersion: DeviceInfoHelper.appVersion(),
            environment: self.buildConfig.apnsEnvironment,
            distribution: self.buildConfig.distribution,
            apnsTokenHex: apnsTokenHex,
            gatewayIdentity: gatewayIdentity)
        let registrationState = PushRelayRegistrationStore.RegistrationState(
            relayHandle: response.relayHandle,
            sendGrant: response.sendGrant,
            relayOrigin: relayOrigin,
            gatewayDeviceId: gatewayIdentity.deviceId,
            relayHandleExpiresAtMs: response.expiresAtMs,
            tokenDebugSuffix: Self.normalizeTokenSuffix(response.tokenSuffix),
            lastAPNsTokenHashHex: tokenHashHex,
            installationId: installationId,
            lastTransport: self.buildConfig.transport.rawValue)
        _ = PushRelayRegistrationStore.saveRegistrationState(registrationState)
        return try Self.encodePayload(
            RelayGatewayPushRegistrationPayload(
                relayHandle: response.relayHandle,
                sendGrant: response.sendGrant,
                gatewayDeviceId: gatewayIdentity.deviceId,
                installationId: installationId,
                topic: topic,
                environment: self.buildConfig.apnsEnvironment.rawValue,
                distribution: self.buildConfig.distribution.rawValue,
                tokenDebugSuffix: registrationState.tokenDebugSuffix))
    }

    private static func isExpired(_ expiresAtMs: Int64?) -> Bool {
        guard let expiresAtMs else { return true }
        let nowMs = Int64(Date().timeIntervalSince1970 * 1000)
        // Refresh shortly before expiry so reconnect-path republishes a live handle.
        return expiresAtMs <= nowMs + 60_000
    }

    private static func sha256Hex(_ value: String) -> String {
        let digest = SHA256.hash(data: Data(value.utf8))
        return digest.map { String(format: "%02x", $0) }.joined()
    }

    private static func normalizeTokenSuffix(_ value: String?) -> String? {
        guard let value else { return nil }
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        return trimmed.isEmpty ? nil : trimmed
    }

    private static func encodePayload(_ payload: some Encodable) throws -> String {
        let data = try JSONEncoder().encode(payload)
        guard let json = String(data: data, encoding: .utf8) else {
            throw PushRelayError.relayMisconfigured("Failed to encode push registration payload as UTF-8")
        }
        return json
    }
}