AppleClientSecret.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.ev_server.security

import java.nio.file.Files
import java.nio.file.Path
import java.security.KeyFactory
import java.security.PrivateKey
import java.security.Signature
import java.security.spec.PKCS8EncodedKeySpec
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.util.Base64

/**
 * The client secret of Sign in with Apple: a JWT signed (ES256) with the key downloaded from the Apple
 * developer account. Apple refuses a secret that lives longer than six months, so a fixed value in
 * APPLE_CLIENT_SECRET eventually stops sign-ins; this class signs a fresh one and renews it every month.
 *
 * See https://developer.apple.com/documentation/accountorganizationaldatasharing/creating-a-client-secret
 */
class AppleClientSecret(
    private val teamId: String,
    private val keyId: String,
    private val clientId: String,
    privateKey: String,
    private val clock: Clock = Clock.systemUTC(),
) {
    private val key: PrivateKey = readKey(privateKey)

    @Volatile private var secret: String? = null
    @Volatile private var issuedAt: Instant = Instant.EPOCH

    init {
        require(teamId.matches(IDENTIFIER)) { "APPLE_TEAM_ID doit contenir les 10 caractères de l’équipe Apple." }
        require(keyId.matches(IDENTIFIER)) { "APPLE_KEY_ID doit contenir les 10 caractères de la clé Apple." }
    }

    fun current(): String {
        val now = Instant.now(clock)
        secret?.takeIf { Duration.between(issuedAt, now) < RENEWAL }?.let {
            return it
        }
        return sign(now).also {
            secret = it
            issuedAt = now
        }
    }

    fun sign(now: Instant): String {
        val encoder = Base64.getUrlEncoder().withoutPadding()
        val header = encoder.encodeToString("""{"alg":"ES256","kid":"$keyId"}""".toByteArray())
        val claims =
            encoder.encodeToString(
                (
                    """{"iss":"$teamId","iat":${now.epochSecond},"exp":${now.plus(LIFETIME).epochSecond},""" +
                        """"aud":"https://appleid.apple.com","sub":"${clientId.replace("\"", "")}"}"""
                    )
                    .toByteArray()
            )
        val signer = Signature.getInstance("SHA256withECDSAinP1363Format")
        signer.initSign(key)
        signer.update("$header.$claims".toByteArray())
        return "$header.$claims.${encoder.encodeToString(signer.sign())}"
    }

    private companion object {
        val IDENTIFIER = Regex("[A-Z0-9]{10}")

        /** Apple accepts at most 15 777 000 seconds (six months). */
        val LIFETIME: Duration = Duration.ofDays(150)
        val RENEWAL: Duration = Duration.ofDays(30)

        fun readKey(value: String): PrivateKey {
            val pem = if (value.contains("BEGIN")) value else Files.readString(Path.of(value))
            val encoded =
                pem.replace("\\n", "\n")
                    .lineSequence()
                    .filterNot { it.startsWith("-----") }
                    .joinToString("")
                    .filterNot(Char::isWhitespace)
            return KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded)))
        }
    }
}